NPOI 中的 Cell Borders 实际上是如何工作的?

How do Cell Borders in NPOI actually work?

我目前正在使用 NPOI 在 C# 中创建一些 Excel 工作表。当我为一些单元格设置不同的边框时,我遇到了一些奇怪的行为。 例如,如果我希望第一个单元格 (0,0) 在右边有一个边框,第二个单元格 (0,1) 在右边和底部有一个边框,我写:

XSSFWorkbook wb = new XSSFWorkbook();
ISheet sheet = wb.CreateSheet();

IRow row = sheet.CreateRow(0);
ICell cell = row.CreateCell(0);
ICellStyle styleRight = wb.CreateCellStyle();
styleRight.BorderRight = BorderStyle.Medium;
cell.CellStyle = styleRight;

row = sheet.CreateRow(1);
cell = row.CreateCell(0);
ICellStyle styleBottomRight = wb.CreateCellStyle();
styleBottomRight.BorderRight = BorderStyle.Medium;
styleBottomRight.BorderBottom = BorderStyle.Medium;
cell.CellStyle = styleBottomRight;

这弄乱了我的结果,并给我的第一个单元格 (0,0) 也提供了底部边框。

但是,如果我切换第二个单元格样式的边框顺序:

row = sheet.CreateRow(1);
cell = row.CreateCell(0);
ICellStyle styleBottomRight = wb.CreateCellStyle();
styleBottomRight.BorderBottom = BorderStyle.Medium;
styleBottomRight.BorderRight = BorderStyle.Medium;
cell.CellStyle = styleBottomRight;

我得到了我想要的结果,在我的第一个单元格上有一个边框,在第二个单元格上有两个边框。

为什么会这样?为什么这两个命令的顺序会改变结果?为什么 styleBottomRight 会影响第一个单元格的样式? 我在 .Net Core 3.1

中使用 NPOI v2.5.1

看起来像是 NPOI 的一个错误,因为第一个案例生成了两个边框:

<borders count="2">
  <border>
    <left/>
    <right/>
    <top/>
    <bottom/>
    <diagonal/>
  </border>
  <border>
     <left/>
     <right style="medium"/>
     <top/>
     <bottom style="medium"/>
     <diagonal/>
  </border>

并且两种样式都引用最后一个边框。

第二种情况:

<borders count="3">
    <border>
        <left/>
        <right/>
        <top/>
        <bottom/>
        <diagonal/>
    </border>
    <border>
        <left/>
        <right style="medium"/>
        <top/>
        <bottom/>
        <diagonal/>
    </border>
    <border>
        <left/>
        <right style="medium"/>
        <top/>
        <bottom style="medium"/>
        <diagonal/>
    </border>
</borders>

并且样式引用到第二个和第三个边框。

无论如何,如果您明确设置边框的值,命令的顺序将不重要:

        XSSFWorkbook wb = new XSSFWorkbook();
        ISheet sheet = wb.CreateSheet();

        IRow row = sheet.CreateRow(0);
        ICell cell = row.CreateCell(0);
        ICellStyle styleRight = wb.CreateCellStyle();
        styleRight.BorderBottom = BorderStyle.None;
        styleRight.BorderRight = BorderStyle.Medium;
        cell.CellStyle = styleRight;
        
        row = sheet.CreateRow(2);
        cell = row.CreateCell(0);
        ICellStyle styleBottomRight = wb.CreateCellStyle();                        
        styleBottomRight.BorderBottom = BorderStyle.Medium;
        styleBottomRight.BorderRight = BorderStyle.Medium;
        cell.CellStyle = styleBottomRight;