具有 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);```

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...