阅读大型XLSX文件

我有一个应用程序必须读取excel并将其转换为数组。 到现在为止还挺好。 一切工作文件,直到我试图转换一个更大的文件。 我尝试OpenXML并尝试SAX方法:

using (SpreadsheetDocument xlsx = SpreadsheetDocument.Open(filePath, false)) { WorkbookPart workbookPart = xlsx.WorkbookPart; List<List<string>> parsedContent = new List<List<string>>(); foreach (WorksheetPart worksheet in workbookPart.WorksheetParts) { OpenXmlReader xlsxReader = OpenXmlReader.Create(worksheet); while (xlsxReader.Read()) { } } } 

这适用于范围在1 – 10MB的文件。 我的问题是当我尝试加载10 + MB文件。 结果是OutOfMemoryException。 如何正确读取大块数据? 如何做到记忆效率?

Ps我尝试像ClosedXML,EPPlus和其他一些库。

每个解决scheme将不胜感激。 先谢谢你

如果你打算只对excel文件内容进行读取,我build议你使用ExcelDataReader库,而不是链接 ,它将工作表数据提取到一个DataSet对象中。

  IExcelDataReader reader = null; string FilePath = "PathToExcelFile"; //Load file into a stream FileStream stream = File.Open(FilePath, FileMode.Open, FileAccess.Read); //Must check file extension to adjust the reader to the excel file type if (Path.GetExtension(FilePath).Equals(".xls")) reader = ExcelReaderFactory.CreateBinaryReader(stream); else if (Path.GetExtension(FilePath).Equals(".xlsx")) reader = ExcelReaderFactory.CreateOpenXmlReader(stream); if (reader != null) { //Fill DataSet DataSet content = reader.AsDataSet(); //Read.... } 

使用ExcelDataReader 。 通过Nuget安装很容易,只需要几行代码:

的NuGet:

 Install-Package ExcelDataReader 

用法:

  using (FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read)) { using (IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream)) { DataSet result = excelReader.AsDataSet(); foreach (DataRow dr in result[0]) { //Do stuff } } }