NPOI导出EXCEL部分样式不起作用

在使用NPOI导出excel的时候,设置cell样式,数据量多余6条之后,在后面几条数据没有样式(边框,对其,换行等)。

原因是设置CellStyle的时候把CreateCellStyle放在循环列集合里边,原版代码有问题的代码

HSSFRow dataRow = (HSSFRow)sheet.CreateRow(rowIndex);
foreach (DataColumn column in dtSource.Columns)
{
    HSSFCell newCell = (HSSFCell)dataRow.CreateCell(column.Ordinal);
    string drValue = row[column].ToString();
    switch (column.DataType.ToString())
    {
        case "System.String":
            {
                HSSFCellStyle strStyle = (HSSFCellStyle)workbook.CreateCellStyle();
                strStyle.BorderBottom = BorderStyle.Thin;
                strStyle.BorderTop = BorderStyle.Thin;
                strStyle.BorderLeft = BorderStyle.Thin;
                strStyle.BorderRight = BorderStyle.Thin;
                //strStyle.VerticalAlignment = VerticalAlignment.Center;
                strStyle.Alignment = HorizontalAlignment.Left;
                switch (detail.Format)
                {
                    case ExportFormat.Normal:
                        //strStyle.Alignment = HorizontalAlignment.Center;
                        strStyle.Alignment = HorizontalAlignment.Left;
                        break;
                    case ExportFormat.Formatted:
                        strStyle.WrapText = true;
                        break;
                }
                newCell.SetCellValue(drValue);
                newCell.CellStyle = strStyle;
                break;
            }
    }
}

 解决问题,需要将该样式提取到foreach外面就可以解决了

HSSFRow dataRow = (HSSFRow)sheet.CreateRow(rowIndex);
HSSFCellStyle strStyle = (HSSFCellStyle)workbook.CreateCellStyle();
strStyle.BorderBottom = BorderStyle.Thin;
strStyle.BorderTop = BorderStyle.Thin;
strStyle.BorderLeft = BorderStyle.Thin;
strStyle.BorderRight = BorderStyle.Thin;
foreach (DataColumn column in dtSource.Columns)
{
    HSSFCell newCell = (HSSFCell)dataRow.CreateCell(column.Ordinal);
    string drValue = row[column].ToString();
    switch (column.DataType.ToString())
    {
        case "System.String":
            {
                //strStyle.VerticalAlignment = VerticalAlignment.Center;
                strStyle.Alignment = HorizontalAlignment.Left;
                switch (detail.Format)
                {
                    case ExportFormat.Normal:
                        //strStyle.Alignment = HorizontalAlignment.Center;
                        strStyle.Alignment = HorizontalAlignment.Left;
                        break;
                    case ExportFormat.Formatted:
                        strStyle.WrapText = true;
                        break;
                }
                newCell.SetCellValue(drValue);
                newCell.CellStyle = strStyle;
                break;
            }
    }
}

  

原文地址:https://www.cnblogs.com/zbfamily/p/9408604.html