我在解析excel文件时遇到了问题。我的文件有超过5000行。当我解析它,它花了很长时间我想问是否有更好的方法这样做。
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;
}
这是我的代码。
答案 0 :(得分:3)
您的问题是您一次只读一个单元格,这对于读取一系列单元格来说非常昂贵且效率低下。
下面的简单示例
Excel.Range range = worksheet.get_Range("A"+i.ToString(), "J" + i.ToString());
System.Array myvalues = (System.Array)range.Cells.Value;
string[] strArray = ConvertToStringArray(myvalues);
基本示例的链接 Read all the cell values from a given range in excel
答案 1 :(得分:2)
我建议不要使用interop,而是使用odbc连接获取excel数据。这将允许您将excel文件视为数据库并使用sql语句来读取所需的数据。
答案 2 :(得分:0)
如果这是一个选项,如果你的表格结构简单,我建议尝试将文件导出到.csv并应用简单的字符串处理逻辑。
您可能还想尝试Igos的消化。
答案 3 :(得分:0)
一种方法是使用ClosedXML库之类的东西来直接读取.xlsx文件,而不是通过Excel互操作。