我從Excel導出數據到DataTable,但是當我的Excel文件中包含大量行我得到一些性能問題......如何大量數據加載到數據表
public DataView LoadFromExcel()
{
Microsoft.Office.Interop.Excel.Application application =
new Microsoft.Office.Interop.Excel.Application();
Workbook workbook = null;
Worksheet worksheet = null;
string filename = null;
OpenFileDialog file = new OpenFileDialog();
if (true == file.ShowDialog())
{
filename = file.FileName;
}
workbook = application.Workbooks.Open(filename, true, true);
worksheet = workbook.Sheets[1];
Range range = worksheet.UsedRange;
int row = range.Rows.Count;
int columns = range.Columns.Count;
System.Data.DataTable dt = new System.Data.DataTable();
for (int i = 1; i <= columns; i++)
{
dt.Columns.Add((range.Cells[1, i] as Range).Value2.ToString());
}
for (row = 2; row <= range.Rows.Count; row++)
{
DataRow dr = dt.NewRow();
for (int column = 1; column <= range.Columns.Count; column++)
{
dr[column - 1] = (range.Cells[row, column] as
Microsoft.Office.Interop.Excel.Range).Value2.ToString();
}
dt.Rows.Add(dr);
dt.AcceptChanges();
}
workbook.Close(true, Missing.Value, Missing.Value);
application.Quit();
return dt.DefaultView;
}
有任何方式我可以解決這個問題?請幫忙。
您不必一次性將所有記錄加載到內存中!響應式擴展(Rx)可能有助於數據流,並且在讀取記錄時,您只需訂閱它並在運行時處理它。 – David
使用Interop很慢。你最好看看沒有它的讀取excel文件的.Net庫。 (Flexcel,Gembox,有很多[](http://stackoverflow.com/q/15828/861716))。 –