导出数据时出现OutOfMemoryException

时间:2018-05-21 15:09:25

标签: c# out-of-memory openxml

我正在尝试构建将数据导出为xlsx格式的导出功能。我已经完成了csv并且它运行良好,但是我在导出大于60,000条记录的数据方面遇到了麻烦。 任何人都可以帮助解决这个难题吗?

uint sheetId = 1;
if (sheets.Elements<DocumentFormat.OpenXml.Spreadsheet.Sheet>().Count() > 0)
{
    sheetId =
        sheets.Elements<DocumentFormat.OpenXml.Spreadsheet.Sheet>().Select(s => s.SheetId.Value).Max() + 1;
}

DocumentFormat.OpenXml.Spreadsheet.Sheet sheet = new DocumentFormat.OpenXml.Spreadsheet.Sheet() { Id = relationshipId, SheetId = sheetId, Name = table.TableName };
sheets.Append(sheet);

DocumentFormat.OpenXml.Spreadsheet.Row headerRow = new DocumentFormat.OpenXml.Spreadsheet.Row();

int iCol = 1;
List<String> columns = new List<string>();
foreach (System.Data.DataColumn column in table.Columns)
{
    columns.Add(column.ColumnName);

    DocumentFormat.OpenXml.Spreadsheet.Cell cell = new DocumentFormat.OpenXml.Spreadsheet.Cell();
    cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String;
    cell.CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue(column.ColumnName);
    cell.CellReference = ExcelColumnLetter(iCol).ToString().Trim() + "1";
    headerRow.AppendChild(cell);

    iCol++;
}

sheetData.AppendChild(headerRow);

int iRow = 2;
foreach (System.Data.DataRow dsrow in table.Rows)
{
    iCol = 1;
    DocumentFormat.OpenXml.Spreadsheet.Row newRow = new DocumentFormat.OpenXml.Spreadsheet.Row();
    foreach (String col in columns)
    {

        DocumentFormat.OpenXml.Spreadsheet.Cell cell = new DocumentFormat.OpenXml.Spreadsheet.Cell();
        cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String;
        cell.CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue(dsrow[col].ToString()); //
        cell.CellReference = ExcelColumnLetter(iCol).ToString().Trim() + iRow.ToString().Trim();
        newRow.AppendChild(cell);
        iCol++;
    }
    sheetData.AppendChild(newRow);
    iRow++;
}
workbook.Close();

0 个答案:

没有答案