首页 > 解决方案 > 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()可能会导致意想不到的问题。有没有更清洁的方法来做到这一点?

标签: c#staticreadonlynpoi

解决方案


最后这样做是解决方案。

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

推荐阅读