我使用 OpenXML 将数据表导出到 Excel 文件。
例如,我使用一个包含大约 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));
}
}