parsingexcel文件的最佳做法

我在parsingexcel文件时遇到了一个问题。 我的文件有超过5000行。 当我parsing它的时候,我想问一下这个问题是否有更好的解决方法。

public static List<List<List<string>>> ExtractData(string filePath) { List<List<List<string>>> Allwork = new List<List<List<string>>>(); Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application(); Microsoft.Office.Interop.Excel.Workbook workBook = excelApp.Workbooks.Open(filePath); foreach (Microsoft.Office.Interop.Excel.Worksheet sheet in workBook.Worksheets) { List<List<string>> Sheet = new List<List<string>>(); Microsoft.Office.Interop.Excel.Range usedRange = sheet.UsedRange; //Iterate the rows in the used range foreach (Microsoft.Office.Interop.Excel.Range row in usedRange.Rows) { List<string> Rows = new List<string>(); String[] Data = new String[row.Columns.Count]; for (int i = 0; i < row.Columns.Count; i++) { try { Data[i] = row.Cells[1, i + 1].Value2.ToString(); Rows.Add(row.Cells[1, i + 1].Value2.ToString()); } catch { Rows.Add(" "); } } Sheet.Add(Rows); } Allwork.Add(Sheet); } excelApp.Quit(); return Allwork; } 

这是我的代码。

你的问题是,你一次只读一个单元格,这是非常昂贵和低效的尝试阅读一系列的单元格。

下面的简单例子

 Excel.Range range = worksheet.get_Range("A"+i.ToString(), "J" + i.ToString()); System.Array myvalues = (System.Array)range.Cells.Value; string[] strArray = ConvertToStringArray(myvalues); 

基本示例的链接读取excel中给定范围的所有单元格值

我build议不要使用interop,而是使用odbc连接获取excel数据。 这将允许您将excel文件视为数据库,并使用sql语句来读取所需的数据。

如果这是一个选项,并且如果你的表有一个简单的结构,我会build议尝试导出文件到.csv和应用简单的string处理逻辑。

你也可能想尝试Igos的消化。

一种方法是使用像ClosedXML库这样的东西直接读取.xlsx文件,而不是通过Excel互操作。