1. 程式人生 > >c#使用Npoi 提示 Excel匯出報錯 The maximum number of cell styles was exceeded. You can define up to 4000

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方法中傳入此物件即可