如何在c#(NPOI)中使用xssf创建特定的单元格样式

问题描述 投票:0回答:1

我正在使用c#中的NPOI从头开始创建一个excel xlsx文件,并且需要为每个单元格设置特定的单元格样式。但据我所知,每当我改变一个细胞的细胞样式时,它就会修改另一个不相关的细胞。

每次我创建一个单元格时,我都会使用我的XSSFWorkbook.CreateCellStyle()指定之前创建的Cellstyle。我认为它应该是一个特定的单元格样式。但是我发现它不是真的,它似乎与之前或之后创建的单元格相同。尽管我调用XSSFWorkbook.CreateCellStyle()并为我正在创建的每个单元格设置它。

以下是我创建单元格的方法:


 for (var i = 0; i < nbCellules; i++)
    {
        var cell = row.CreateCell(i);
        var style = xssfwb.CreateCellStyle();
        cell.CellStyle = xssfwb.CreateCellStyle();
        cell.CellStyle.BorderLeft = GetLeftBorderStyleFromIndex(i);
        cell.CellStyle.BorderRight = GetRightBorderStyleFromIndex(i);
    }

使用该代码,我执行以下操作:

   row.GetCell(0).CellStyle.BorderBottom = BorderStyle.Thick;

我认为只有那个特定的细胞才会受到影响。 但是,每一行现在都有一个厚底边框。

有人知道我哪里错了吗?

c# excel npoi xssf
1个回答
0
投票

好吧,似乎我已经理解了发生了什么。

请注意,没有人回答我,所以这是一个经验回答。

看来,如果你这样做:

   var cell1 = sheet.GetRow(0).CreateCell(0);
   var style = workBook.CreateCellStyle();
   style.BorderBottom = BorderStyle.Thick;

   var cell2 = sheet.GetRow(1).CreateCell(0);
   var style = workBook.CreateCellStyle();
   style.BorderBottom = BorderStyle.Thick;

   // Now if you decide to change something from the style of cell2
   cell2.CellStyle.BorderRight = BorderStyle.Dotted;

   // it seems that cell1 now has BorderStyle.Dotted pour son Cellstyle.BorderRight

我不确切知道发生了什么,但似乎一旦CellStyle受到细胞的影响,如果他与另一个细胞的CellStyle相同,那么它就不会被克隆,而是被共享。

然后我描述了每个cellStyle,然后将它们影响到一个单元格,现在它起作用了。

请随时与我联系以获取更多详情!

© www.soinside.com 2019 - 2024. All rights reserved.