NPOI-Styling合并细胞

时间:2018-04-10 07:13:20

标签: npoi

我想改变ForegroundColor并在合并单元格的中心设置文本。

NPOI可以做到吗?

这是我的表: enter image description here

我知道如何设置border.But我找不到有关更改合并单元格样式的资源。

有人可以给我一些提示或帮助吗?

2 个答案:

答案 0 :(得分:1)

对于Row,你必须像这样单独设置

XSSFSheet sheet = (XSSFSheet)workbook.CreateSheet("Template");
XSSFCellStyle headerStyle = (XSSFCellStyle)workbook.CreateCellStyle();
headerStyle.WrapText = true;
headerStyle.FillForegroundColor = IndexedColors.LightBlue.Index;
headerStyle.Alignment = HorizontalAlignment.Center;
var row = sheet.CreateRow(0);
row.Cells[YourheaderIndex].CellStyle = headerStyle;

对于列,您可以设置类似

的样式
XSSFCellStyle defaultStyle = (XSSFCellStyle)workbook.CreateCellStyle();
defaultStyle.WrapText = true;
defaultStyle.Alignment = HorizontalAlignment.Left;
defaultStyle.VerticalAlignment = VerticalAlignment.Top;
sheet.SetDefaultColumnStyle(YourheaderIndex, defaultStyle);

要将样式应用于合并单元格,您可以尝试这种方法,虽然代码未经测试,但它会为NPOI中的可用方法提供好的建议

int mergedRegions = sheet.NumMergedRegions;
for (int regions = 0; regions < mergedRegions; regions++)
{
    CellRangeAddress mergedRegionIndex = sheet.GetMergedRegion(regions);

    for (int currentRegion = mergedRegionIndex.FirstRow; currentRegion < mergedRegionIndex.LastRow; currentRegion++)
    {
        var currentRow = sheet.GetRow(currentRegion);

        for (int currentCell = mergedRegionIndex.FirstColumn; currentCell < mergedRegionIndex.LastColumn; currentCell++)
        {
            // sheet.SetDefaultColumnStyle(i, mandatoryCellStyle);
            currentRow.Cells[currentCell].CellStyle = headerStyle;
        }
    }
}

答案 1 :(得分:1)

  var cra = new NPOI.SS.Util.CellRangeAddress(rowNum, rowNum + 6, 2, 5);
            excelSheet.AddMergedRegion(cra);          
            RegionUtil.SetBorderBottom(1, cra, excelSheet, workbook);//Bottom border  
            RegionUtil.SetBorderLeft(1, cra, excelSheet, workbook);//Left border  
            RegionUtil.SetBorderRight(1, cra, excelSheet, workbook);//Right border  
            RegionUtil.SetBorderTop(1, cra, excelSheet, workbook);