c#使用Npoi 提示 Excel导出报错 The maximum number of cell styles was exceeded. You can define up to 4000

在使用NPOI 导出EXCEL的时候 提示
The maximum number of cell styles was exceeded. You can define up to 4000 styles in a .xls workbook
出现此问题 原因如下:
private static void SetFontSize(IFont font,IWorkbook wk,string content, IRow rows,int row)
{
ICell cell = rows.CreateCell(row);
cell.SetCellValue(content);
// 在导出的EXCEL记录多的时候执行如下代码出现的错误:
ICellStyle cellsytle = wk.CreateCellStyle();
cellsytle.SetFont(font);
cell.CellStyle = cellsytle;
}

因为SetFontSize 方法是在循环中执行,此句代码在方法中,因此报错,解决方法
ICellStyle cellsytle = wk.CreateCellStyle(); 这句代码应该在循环外执行方可
解决方法
ICellStyle cellsytle = wk.CreateCellStyle(); \此对象在循环外声明
for (int i = 0; i < dgv.Rows.Count; i++)
{
int cx = Convert.ToInt32(dgv.Rows[i].Cells[0].Value);
string cbcx = dgv.Rows[i].Cells[1].Value.ToString();
string yshdm = dgv.Rows[i].Cells[2].Value.ToString();
string yshmc = dgv.Rows[i].Cells[3].Value.ToString();
string yshdz = dgv.Rows[i].Cells[4].Value.ToString();
string cbxldm = dgv.Rows[i].Cells[5].Value.ToString();
string cby = dgv.Rows[i].Cells[6].Value.ToString();
string zt = dgv.Rows[i].Cells[7].Value.ToString();
string gyh = dgv.Rows[i].Cells[8].Value.ToString(); ;
IRow rows = sheet.CreateRow(index);
index++;
SetFontSizeTOInt(font, wk,cellsytle,cx, rows, 0);
SetFontSize(font, wk, cellsytle, cbcx, rows, 1);
SetFontSize(font, wk, cellsytle, yshdm, rows, 2);
SetFontSize(font, wk, cellsytle, yshmc, rows, 3);
SetFontSize(font, wk, cellsytle, yshdz, rows, 4);
SetFontSize(font, wk, cellsytle, cbxldm, rows, 5);
SetFontSize(font, wk, cellsytle, cby, rows, 6);
SetFontSize(font, wk, cellsytle, zt, rows, 7);
SetFontSize(font, wk, cellsytle, gyh, rows, 8);
}
循环内在SetFontSize方法中传入此对象即可

猜你喜欢

转载自blog.csdn.net/sd6275832ght/article/details/83058750