2012-11-12 28 views
0

我使用OpenXML將數據表導出到Excel文件。OpenXML內存泄漏

例如,我使用一張約250,000行約10列的表格。將其導出到Excel時,需要大約1.2 GB的內存才能完成該操作,有時會拋出OutOfMemoryException

有沒有解決我的問題的方法?

這裏是我的代碼

 ExcelDocument excelDocument = new ExcelDocument(); 
     excelDocument.CreatePackage(exportFile); 

     //populate the data into the spreadsheet 
     using (SpreadsheetDocument spreadsheet = 
      SpreadsheetDocument.Open(exportFile, true)) 
     { 
      WorkbookPart workbook = spreadsheet.WorkbookPart; 
      //create a reference to Sheet1 
      WorksheetPart worksheet = workbook.WorksheetParts.Last(); 
      SheetData data = worksheet.Worksheet.GetFirstChild<SheetData>(); 

      //add column names to the first row 
      Row header = new Row(); 
      header.RowIndex = (UInt32) 5; 

      foreach (DataColumn column in table.Columns) 
      { 
       Stylesheet styleSheet = workbook.WorkbookStylesPart.Stylesheet; 

       //build the formatted header style 
       UInt32Value headerFontIndex = 
        createFont(
         styleSheet, 
         "Arial", 
         9, 
         true, 
         System.Drawing.Color.White); 
       //set the background color style 
       UInt32Value headerFillIndex = 
        createFill(
         styleSheet, 
         System.Drawing.Color.SlateGray); 
       //create the cell style by combining font/background 
       UInt32Value headerStyleIndex = 
        createCellFormat(
         styleSheet, 
         headerFontIndex, 
         headerFillIndex, 
         null); 
       Cell headerCell = createTextCell(
        table.Columns.IndexOf(column) + 1, 
        5, 
        column.ColumnName, headerStyleIndex); 

       header.AppendChild(headerCell); 
      } 
      data.AppendChild(header); 

      //loop through each data row 
      DataRow contentRow; 
      for (int i = 0; i < table.Rows.Count; i++) 
      { 
       contentRow = table.Rows[i]; 
       data.AppendChild(createContentRow(contentRow, i + 6)); 
      } 
     } 

回答

1

問題處置SpreadsheetDocument是什麼時候帶太多的時間,它似乎廢棄時,所有的數據刷新到Excel工作表,所以我吐唾沫其中創建,使Excel表每個文件只有30,000條記錄,並強制垃圾收集器運行並解決了我的問題