使用NPOI导出Excel ICell调用过多 内存溢出
使用NPOI导出Excel ICell调用过多 内存溢出
datagridview一共有七十多列、六万多行 进行到四万多行的时候就提示'引发类型为“System.OutOfMemoryException”的异常。'
求高手帮忙看下
private void button3_Click(object sender, EventArgs e)
{
if (dgExcel.Rows.Count > 0)
{
SaveFileDialog save = new SaveFileDialog();
save.Filter = "xls文件|*.xls|所有文件|*.*";
save.FileName = "Demo.xls";
if (save.ShowDialog() == DialogResult.OK)
{
int irow = dgExcel.Rows.Count;
int n = (irow + 30000 - 1) / 30000;
using (HSSFWorkbook workbook = new HSSFWorkbook())
{
for (int i = 1; i <= n; i++)
{
if (i == n)
OutIntoExcel(workbook, i, i * 30000 - 30000, irow - 1);
else
OutIntoExcel(workbook, i, i * 30000 - 30000, i * 30000 - 1);
}
FileStream file = new FileStream(save.FileName, FileMode.Create);
workbook.Write(file);
file.Close();
}
MessageBox.Show("数据导出成功,请查看!", "数据导出", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
public void OutIntoExcel(HSSFWorkbook workbook, int i, int rowf, int rowt)
{
ISheet sheet1 = workbook.CreateSheet("Sheet" + i.ToString());
IRow row;
ICell cell;
int rows = rowf;
for (int rowIndex = 0; rowIndex
{
row = sheet1.CreateRow(rowIndex);
for (int colIndex = 0; colIndex
{
cell = row.CreateCell(colIndex);
if (rowIndex == 0)
cell.SetCellValue(dgExcel.Columns[colIndex].HeaderText);
else
cell.SetCellValue(dgExcel[colIndex, rows].Value.ToString());
}
if (rowIndex != 0)
rows += 1;
if (rows == rowt + 1)
break;
}
}
------解决思路----------------------
每次更新1000条,循环更新
------解决思路----------------------
xls格式是03,它不支持那么多数据
你需要改成xlsx,也就是07
当然07也有限制,但是至少要比03大的多了
------解决思路----------------------
要么就自己做判断,如果超过了多少数据,就创建新的工作簿存放,不要都放一个工作簿里
------解决思路----------------------
if(i==1000) //每当到1000行时写入一次
{
....
FileStream file = new FileStream(save.FileName, FileMode.OpenOrCreate);
workbook.Write(file);
file.close();
GC.Collect();
workbook = new HSSFWorkbook();//重新打开workbook
}
大概就是这个意思吧..
------解决思路----------------------
看看这个吧
https://npoi.codeplex.com/discussions/540101