NPOI插件的弊端
剛來公司的時候公司軟體匯入匯出操作都使用微軟的office組件來實作,大家應該都知道這個組件有很大的弊端,就是運行主機上面必須安裝office組件才可進行使用,不然無法進行匯入匯出操作,之前公司軟體部門給的做法就是直接讓客戶安裝Office就可以解決,
我接手后知道這個弊端,將插件進行了替換,使用網上比較流行的NPOI插件,基本上很少出現關于軟體匯入匯出資料的反饋,但由于之前的軟體需求基本都是少量資料的匯入匯出,NPOI都可以滿足,現在新需求要求匯入匯出超過40w行的資料,NPOI插件就暴露出來弊端,在資料少的時候使用.xlsx的XFFSWorkbook類就可以實作,但是資料量超過某一個閥值,XFFSWorkbook就出現了例外,爆出記憶體溢位的訊息,而且宣告和訪問時速度特別慢,感覺是組件內部在處理大資料檔案時存在問題,
在網上查找發現NPOI對于大資料的處理有一個SXSSFWorkbook,它是NPOI專門來處理大資料檔案的,我在使用程序中,當寫入時,沒問題可以使用,但是效率方面很差,可是在讀取時,根本無法使用,因為它在使用程序中必須宣告XFFWorkbook才可以,可是宣告它的話就會遇到記憶體溢位問題,網上還有說直接使用xml形式來讀取,但是xml格式需要自己去定義和決議,特別麻煩,故沒有采用,
//宣告處理.xlsx檔案的方法(小檔案)
IWorkbook workbook=new XSSFWorkbook();
//宣告處理.xlsx檔案的方法(大檔案)
IWorkbook workbook=new XSSFWorkbook();
IWorkbook wb=new SXSSFWorkbook(workbook);
ExcelDataReader插件
在處理讀取.xlsx檔案時,在nuget中發現了ExcelDataReader插件,在做了demo后,對于40w行的讀取很方便,而且速度特別快,推薦大家使用,
FileStream fs = null;
IExcelDataReader excelReader = null;
try
{
fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
excelReader = ExcelReaderFactory.CreateOpenXmlReader(fs);
int readIndex = 0;
int rowCount = excelReader.RowCount; //所有的行
DataRow dr;
object tempValue;
while (excelReader.Read())
{
dr = data.NewRow();
if (readIndex == startReadRowCount)
{
++readIndex;
continue;
}
//讀取Excel中的頭檔案資訊
if (readIndex <startReadRowCount)
{
dr[0] = excelReader.GetValue(0).ToString();
tempValue = https://www.cnblogs.com/netxiaohui/archive/2021/04/24/excelReader.GetValue(1);
if (tempValue==null)
{
dr[1] = DBNull.Value;
}
else
{
dr[1] = excelReader.GetValue(1).ToString();
}
dr[2] = DBNull.Value;
dr[3] = DBNull.Value;
dr[4] = DBNull.Value;
dr[5] = DBNull.Value;
dr[6] = DBNull.Value;
}
else
{
dr[0] = excelReader.GetValue(0).ToString();
dr[1] = excelReader.GetValue(1).ToString();
dr[2] = Convert.ToDouble(excelReader.GetValue(2));
tempValue = excelReader.GetValue(3);
if (tempValue == null)
{
dr[3] = DBNull.Value;
}
else
{
dr[3] = Convert.ToDouble(excelReader.GetValue(3));
}
dr[4] = Convert.ToDouble(excelReader.GetValue(4));
dr[5] = Convert.ToDouble(excelReader.GetValue(5));
dr[6] = Convert.ToDouble(excelReader.GetValue(6));
}
data.Rows.Add(dr);
if (worker.CancellationPending) // 如果用戶取消則跳出處理資料代碼
{
e.Cancel = true;
break;
}
worker.ReportProgress(readIndex * 100 / rowCount);//加載進度條
++readIndex;
}
fs.Close();
fs.Dispose();
excelReader.Close();
excelReader.Dispose();
return data;
}
catch (Exception ex)
{
if (worker.CancellationPending) // 如果用戶取消則跳出處理資料代碼
{
e.Cancel = true;
}
if (fs != null)
{
fs.Close();
fs.Dispose();
}
if (excelReader != null)
{
excelReader.Close();
excelReader.Dispose();
}
throw new Exception("" + ex.Message);
}
插件下載地址:
https://www.nuget.org/packages/ExcelDataReader/3.0.0
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/279767.html
標籤:.NET技术
