将数据写入excel时抛出了类型'System.OutOfMemoryException'的异常

时间:2016-05-15 11:30:52

标签: asp.net

我正在尝试在Excel中写入大约200000行并收到错误

  

抛出了'System.OutOfMemoryException'类型的异常

我的代码如下:

DataTable dtS = new DataTable();

dtS = myFucntion();

FileStream fs = new FileStream(Server.MapPath(@"~/Images/Tss_rpt.xlsx"),
                               FileMode.Open, FileAccess.Read);

NPOI.XSSF.UserModel.XSSFWorkbook PBLXSSFWorkbook2 = 
    new NPOI.XSSF.UserModel.XSSFWorkbook(fs);

XSSFSheet PBLsheet2 = (XSSFSheet)PBLXSSFWorkbook2.GetSheet("TssAML");

if (dtS.Rows.Count > 0)
{
    XSSFRow PBLrows;

    for (int i = 0; i < dtS.Rows.Count; i++)
    {
        PBLrows = (XSSFRow)PBLsheet2.CreateRow(i);

        for (int j = 0; j < dtS.Columns.Count; j++)
        {
            PBLrows.CreateCell(j).SetCellValue(dtS.Rows[i][j].ToString());
        }
    }

    PBLrows = null;

    MemoryStream ms = new MemoryStream();

    PBLXSSFWorkbook2.Write(ms);
    ExportDataTableToExcel(ms, "Txn_Aml_rpt.xlsx");
}
else 
{ 
    clsMessageBox.Show("No Record(s) Found !!"); return; 
}

1 个答案:

答案 0 :(得分:0)

添加

Response.Buffer = true;
Response.Clear();

在写数据之前。