编程语言
首页 > 编程语言> > 保存/创建/导出Excel工作表时出现C#-OutOfMemoryException

保存/创建/导出Excel工作表时出现C#-OutOfMemoryException

作者:互联网

开发环境:

>操作系统-Windows 7 64位
> CPU-i5 460M
>内存-8GB
> .NET Framework-4.0
> Excel-Interop-Microsoft Excel 14.0对象库

我正在使用Excel-Interop从DataGridView(dgv)导出Excel文件.

当我保存超过150,000行时

OutOfMemoryException

被抛出.

{
    object[,] valueObjArray = new object[rowCnt, colCnt];
    int rowCnt = dgv.Rows.Count;
    int colCnt = dgv.Columns.Count;

    for (int rowIndex = 0; rowIndex < rowCnt; rowIndex++)
    {
        for (int colIndex = 0; colIndex < colCnt; colIndex++)
        {
            valueObjArray[rowIndex, colIndex] = dgv[colIndex, rowIndex].Value;
        }
    }

    _workSheet.get_Range("A1", Convert.ToChar(colCnt + 64).ToString() + "1").Value2 = headerObjArray;                
    _workSheet.get_Range("A2", Convert.ToChar(colCnt + 64).ToString() + (rowCnt + 1).ToString()).Value2 = valueObjArray;
    _workSheet.get_Range("B2", "B" + (rowCnt+1).ToString()).NumberFormat = "yyyy-mm-dd hh:mm";

    _workBook.SaveAs(path);
}

这是我所知加快速度的最佳方法.

但是,在监视RAM之后,我认为这会导致内存增加.当内存使用量达到约900Mb时,将引发异常.

如何捕获此异常?

解决方法:

尝试分批执行:

//We will call SaveAs method many times and we don't want to be asked
//if a file should be overwritten every time.
xlApp.DisplayAlerts = false

int rowCnt = dgv.Rows.Count;
int colCnt = dgv.Columns.Count;

int batchSize = 100000; //Try to experiment with other values
int currentRow = 0;

object[,] valueObjArray = new object[batchSize, colCnt];

_workSheet.get_Range("A1", Convert.ToChar(colCnt + 64).ToString() + "1").Value2 = headerObjArray;     

while (currentRow < rowCnt)
{
    for (int rowIndex = 0; rowIndex < batchSize && currentRow + rowIndex < rowCnt; rowIndex++)
    {
        for (int colIndex = 0; colIndex < colCnt; colIndex++)
        {
            valueObjArray[rowIndex, colIndex] =             
            dgv[colIndex, currentRow + rowIndex].Value;
        }
    }

    ws.get_Range("A2", Convert.ToChar(colCnt + 64).ToString() + (currentRow + batchSize + 1).ToString()).Value2 = valueObjArray;
    ws.get_Range("B2", "B" + (currentRow + batchSize + 1).ToString()).NumberFormat = "yyyy-mm-dd hh:mm";

    wb.SaveAs("a.xlsx");

    currentRow += batchSize;
}

这样我就可以保存100万行.我使用伪造数据对其进行了测试,因此可能需要进行一些小的更改/修复.

标签:export-to-excel,out-of-memory,excel-interop,c,excel
来源: https://codeday.me/bug/20191119/2032539.html