C# NPOI流读取大文件Excel
时间: 2023-07-29 15:09:40 浏览: 265
当需要读取大文件的Excel时,可以使用NPOI库提供的`SAX`模式来避免内存溢出。以下是示例代码:
```csharp
using NPOI.OpenXmlFormats.Spreadsheet;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System.Data;
using System.IO;
public static DataTable ReadBigExcelToDataTable(string filePath)
{
DataTable dataTable = new DataTable();
using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
XSSFWorkbook workbook = new XSSFWorkbook(fileStream);
XSSFSheet sheet = (XSSFSheet)workbook.GetSheetAt(0);
DataFormatter dataFormatter = new DataFormatter();
foreach (IRow row in sheet)
{
if (row.RowNum == 0)
{
// Add columns
for (int i = 0; i < row.LastCellNum; i++)
{
string columnName = dataFormatter.FormatCellValue(row.GetCell(i));
DataColumn column = new DataColumn(columnName);
dataTable.Columns.Add(column);
}
}
else
{
DataRow dataRow = dataTable.NewRow();
for (int i = 0; i < row.LastCellNum; i++)
{
if (row.GetCell(i) != null)
{
string cellValue = dataFormatter.FormatCellValue(row.GetCell(i));
dataRow[i] = cellValue;
}
}
dataTable.Rows.Add(dataRow);
}
}
}
return dataTable;
}
```
使用方法:
```csharp
DataTable dataTable = ReadBigExcelToDataTable("path/to/big/excel/file.xlsx");
```
注意,由于采用了`SAX`模式,读取大文件的Excel速度比较慢,但能够避免内存溢出的问题。如果需要读取大文件并且速度较快,可以考虑使用其他的库或者工具。
阅读全文