我正在尝试使用 OpenXML 从 ASP.NET Web 服务器中写出 Excel 文件。我有大约 2100 条记录,它需要大约 20-30 秒才能完成。有什么办法可以让它更快吗?从数据库中检索 2100 行只需要几分之一秒。不知道为什么在内存中操作它们会花费更长的时间。
注意:ExcelWriter 是我们的自定义类,但它的所有方法都直接来自此链接中的代码, http: //msdn.microsoft.com/en-us/library/cc861607.aspx
public static MemoryStream CreateThingReport(List<Thing> things, MemoryStream template)
{
SpreadsheetDocument spreadsheet = SpreadsheetDocument.Open(template, true);
WorksheetPart workSheetPart = spreadsheet.WorkbookPart.WorksheetParts.First();
SharedStringTablePart sharedStringPart = spreadsheet.WorkbookPart.GetPartsOfType<SharedStringTablePart>().First();
Cell cell = null;
int index = 0;
//create cell formatting for header text
Alignment wrappedAlignment = new Alignment { WrapText = true };
uint rowOffset = 2;
foreach (Thing t in things)
{
//Received Date
cell = ExcelWriter.InsertCellIntoWorksheet("A", rowOffset, workSheetPart);
index = ExcelWriter.InsertSharedStringItem(t.CreateDate.ToShortDateString(), sharedStringPart);
cell.CellValue = new CellValue(index.ToString());
cell.DataType = new DocumentFormat.OpenXml.EnumValue<CellValues>(CellValues.SharedString);
//Car Part Name
cell = ExcelWriter.InsertCellIntoWorksheet("B", rowOffset, workSheetPart);
index = ExcelWriter.InsertSharedStringItem(t.CarPart.Name, sharedStringPart);
cell.CellValue = new CellValue(index.ToString());
cell.DataType = new DocumentFormat.OpenXml.EnumValue<CellValues>(CellValues.SharedString);
rowOffset++;
}
workSheetPart.Worksheet.Save();
spreadsheet.WorkbookPart.Workbook.Save();
spreadsheet.Close();
return template;