2013-09-28 206 views
3

尝试从内存流向输出流写入数据表时抛出System.OutOfMemoryException时尝试将Excel文件传递给用户的网页。我使用Closed XML在Excel中保存文件,数据表大约包含40K行和150列,大部分包含小数,导出的文件通常为10MB或更大。在导出到excel的时候,大量数据集被攻破的建议技巧是什么?导出到excel抛出System.OutOfMemoryException

这是从封闭的XML,我使用http://closedxml.codeplex.com/wikipage?title=How%20do%20I%20deliver%20an%20Excel%20file%20in%20ASP.NET%3f&referringTitle=Documentation

  public HttpResponseMessage Get() 
      { 
      // Create the workbook 
      var workbook = new XLWorkbook(); 
      Datatable dt = getDataTable(); 
      workbook.Worksheets.Add(dt); 

      // Prepare the response 
      HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK); 
      var memoryStream = new MemoryStream(); // If I put this in a 'using' construct, I never get the response back in a browser. 
      workbook.SaveAs(memoryStream); 
      memoryStream.Seek(0, SeekOrigin.Begin); // Seem to have to manually rewind stream before applying it to the content. 
      response.Content = new StreamContent(memoryStream); 
      response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); 
      response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = "HelloWorld.xlsx" }; 
      return response; 
      } 

回答

3

嗨,您可以通过下面的类型避免内存溢出异常的代码。

  1. 使用reflation方法会减少内存并获得良好的性能。
  2. 通过使用下面的代码片段,仅将值加载到Excel工作表。

代码片段[C#]:

ExcelEngine excelEngine = new ExcelEngine(); 
      IApplication application = excelEngine.Excel; 
      IWorkbook workbook = application.Workbooks.Create(1); //We are using single workbook 
      IWorksheet sheet = workbook.Worksheets[0]; //In this case we are exporting to single ExcelSheet so we marked Worksheets as 0 
      for (int i = 0; i < grid.Model.RowCount; i++) 
      { 
       //Setting Excel cell height based on Grid Cell height 
       sheet.SetRowHeightInPixels(i + 1, set heigth here); 
       for (int j = 0; j < ColumnCount; j++) 
       { 
        int width = Convert.ToInt32(ColumnWidths[j]); //Getting Grid Cell column width 
        sheet.SetColumnWidthInPixels(j + 1, width); //Setting Width for Excel cell 
        sheet.Range[i + 1, j + 1].Text = dt value here; 
       } 
      } 
+0

您能否发布一些有用的链接来解释Reflation Method? – Anusha

3

我偶然发现这个链接OpenXML libraries (alternatives to ClosedXML)上,并EPPlus https://epplus.codeplex.com/作品比ClosedXML要好得多当大量的数据被导出到Excel。 由于EPPlus似乎避开了内存流,至少没有更多的“OutOfMemory”异常,尽管我仍然有兴趣知道他们是如何完成这一任务的,甚至是了解Closed XML和EPPlus之间的区别。

相关问题