尝试将单个excel工作簿的多个Excel工作表中的数据合并到单个工作表中。每个Excel工作表都有5万行,大约80列。由于数据量巨大,应用程序抛出“内存不足”异常。
代码:
using (SpreadsheetDocument doc = SpreadsheetDocument.Open(InputExcelFilePath, false))
{
WorkbookPart wbPart = doc.WorkbookPart;
Sheet mainRosterSheet = wbPart.Workbook.Descendants<Sheet>().Where(s => s.Name == "TestSheet").FirstOrDefault();
Worksheet mainWorksheet = ((WorksheetPart)wbPart.GetPartById(mainRosterSheet.Id)).Worksheet;
SheetData mainSheetdata = (SheetData)mainWorksheet.GetFirstChild<SheetData>();
Sheets sheetcollection = wbPart.Workbook.GetFirstChild<Sheets>();
foreach (Sheet childSheet in sheetcollection)
{
string sheetName = childSheet.Name;
if (sheetName.StartsWith("TestSheet ("))
{
Worksheet childWorksheet = ((WorksheetPart)wbPart.GetPartById(childSheet.Id)).Worksheet;
SheetData childsheetdata = (SheetData)childWorksheet.GetFirstChild<SheetData>(); //Thowing Out of Meory Exception
}
}
}
使用OpenXML库进行excel操作。 如果数据大小受到上述方法的限制,请提出是否有任何可用于合并具有大量数据的excel工作表的帮助程序库。
答案 0 :(得分:0)
我建议您不要一次做一个批量操作,而是一步一步地进行处理,这样可以释放一些内存...类似
WorkbookPart wbPart = doc.WorkbookPart;
Sheet mainRosterSheet = wbPart.Workbook.Descendants<Sheet>().Where(s => s.Name == "TestSheet").FirstOrDefault();
Worksheet mainWorksheet = ((WorksheetPart)wbPart.GetPartById(mainRosterSheet.Id)).Worksheet;
SheetData mainSheetdata = (SheetData)mainWorksheet.GetFirstChild<SheetData>();
Sheets sheetcollection = wbPart.Workbook.GetFirstChild<Sheets>();
foreach (Sheet childSheet in sheetcollection)
{
using (SpreadsheetDocument doc = SpreadsheetDocument.Open(InputExcelFilePath, false))
{
string sheetName = childSheet.Name;
if (sheetName.StartsWith("TestSheet ("))
{
Worksheet childWorksheet = ((WorksheetPart)wbPart.GetPartById(childSheet.Id)).Worksheet;
SheetData childsheetdata = (SheetData)childWorksheet.GetFirstChild<SheetData>(); //Thowing Out of Meory Exception
}
}
}
上面的代码未经测试