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

本文详细解析了使用NPOI导出Excel时遇到的样式数量超过4000个的错误,并提供了有效的解决策略。通过调整CellStyle对象的创建位置,避免了在循环中重复创建样式,从而解决了样式数量限制的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在使用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方法中传入此对象即可

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值