c# - NPOI 的具有 CellStyle 静态值的类
问题描述
[底部更新]
我想要做的:
有一个static readonly
值的类,CellStyles
所以我可以让我的代码构建 excel 文件是这样的:
ICellStyle headerStyle1 = workbook.CreateCellStyle();
headerStyle1 = ExcelStyles.header1;
而不是这样:
headerStyle1.BorderBottom = NPOI.SS.UserModel.BorderStyle.Medium;
headerStyle1.BorderTop = NPOI.SS.UserModel.BorderStyle.Medium;
headerStyle1.BorderLeft = NPOI.SS.UserModel.BorderStyle.Medium;
headerStyle1.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
这将使以后更容易阅读、理解和维护。
到目前为止我所拥有的:我创建了一个名为的类ExcelStyles.cs
,我计划在其中使用public static readonly
变量,这样我就可以调用我需要的那些,我知道如何使用方法来做到这一点,但是CellStyle
理论上应该让它们直接成为对象以后事情就容易多了。这段代码是我试图做的,但显然不起作用,因为它不是正确的语法/方法。
class ExcelStyles
{
public static readonly ICellStyle header1 =
{
header1.BorderBottom = NPOI.SS.UserModel.BorderStyle.Medium;
header1.BorderTop = NPOI.SS.UserModel.BorderStyle.Medium;
}
}
问题:我不知道如何正确执行此操作,并且我已经将头撞到墙上一段时间试图弄清楚我应该如何搜索这个但没有太大成功,我不知道它是否是可能与NPOI
我正在使用: Visual Studio 2019、Windows Forms、C#、.NET Framework 4.7.2、NPOI 2.5.3,它是一个桌面应用程序
更新:在摆弄了一下之后,我得到了这段代码:
class ExcelStyles
{
public static readonly ICellStyle header1 = ((XSSFWorkbook)new XSSFWorkbook()).CreateCellStyle();
static ExcelStyles()
{
header1.BorderBottom = NPOI.SS.UserModel.BorderStyle.Medium;
header1.BorderTop = NPOI.SS.UserModel.BorderStyle.Medium;
header1.BorderLeft = NPOI.SS.UserModel.BorderStyle.Medium;
header1.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
header1.FillPattern = FillPattern.SolidForeground;
header1.VerticalAlignment = VerticalAlignment.Center;
}
}
我这样称呼它:
ICellStyle headerStyle1 = workbook.CreateCellStyle();
headerStyle1.CloneStyleFrom(ExcelStyles.header1);
所以问题发生了变化,到目前为止的测试已经按预期工作,但我担心这((XSSFWorkbook)new XSSFWorkbook()).CreateCellStyle()
可能会导致意想不到的问题。有没有更清洁的方法来做到这一点?
解决方案
最后这样做是解决方案。
public static readonly ICellStyle header1 = new XSSFWorkbook().CreateCellStyle();
static ExcelStyles()
{
header1.FillPattern = FillPattern.SolidForeground;
header1.FillForegroundColor = color;
header1.BorderBottom = NPOI.SS.UserModel.BorderStyle.Medium;
header1.BorderTop = NPOI.SS.UserModel.BorderStyle.Medium;
header1.BorderLeft = NPOI.SS.UserModel.BorderStyle.Medium;
header1.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
header1.VerticalAlignment = VerticalAlignment.Center;
header1.Alignment = HorizontalAlignment.Left;
}
然后应用它
ICellStyle headerStyle1 = workbook.CreateCellStyle();
headerStyle1.CloneStyleFrom(ExcelStyles.header1);```
推荐阅读
- c - 完成 atoi 令牌后,我不能制作 strcpy 吗?
- reactjs - 平台 "win32" 与此模块 (fsevents) 不兼容
- mysql - MySQL 在 my.cnf 文件中设置 innodb_buffer_pool_size - 未找到
- mongodb - 仅当文档不存在时如何将文档添加到 mongo
- css - 如何使用 _app.js (Next.js) 中声明的全局 css 文件中的 css 类
- python - 如何将 Python 脚本添加到 HTML
- php - 如何使用 php 在邮件中提交联系表格?
- python - 腌制数据类的实例
- java - Docker MySQL在超时后丢弃表:连接关闭后不允许操作
- javascript - 使用 PHP 时钟显示“我们明天在 _____ 重新开放”