【问题标题】:How to create specific cellstyles with xssf in c# (NPOI)如何在 c# (NPOI) 中使用 xssf 创建特定的单元格样式
【发布时间】:2019-05-01 19:58:40
【问题描述】:

我正在使用 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】:

    好的,看来我已经明白发生了什么。

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

    如果你这样做:

       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,然后将它们影响到一个单元格,现在它起作用了。

    欢迎联系我了解更多详情!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-25
      • 1970-01-01
      • 2014-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-23
      • 1970-01-01
      相关资源
      最近更新 更多