I use OpenXML to export data table to an Excel file.
For example I use a table with about 250,000 rows and about 10 columns. When exporting it to Excel, it takes about 1.2 GB of memory to do that, and sometimes throws an OutOfMemoryException.
Is there any solution for my problem?
Here’s my code
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));
}
}
The problem was when disposing SpreadsheetDocument it take too many time, it seems that it flushes all data to the excel sheet when disposing , so I spitted excel sheets which are created and make only 30,000 records per file and enforced Garbage Collector to run and solved my problem