Search code examples
npoi

NPOI-Styling merged cell


I want to chenge ForegroundColor and set text in center at merged cell.

Is it possible to do that by NPOI?

This is my table: enter image description here

I know how to set border.But I cant find resources about change merged cell style.

Can someone please give me some tips or help ?


Solution

  • For Row you'll have to set individually like this

    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;
    

    For columns you can set the style like

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

    To apply style to merged cell you can try this approach , code is untested though but it will give good idea for available methods in 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;
            }
        }
    }