阅读一个大的Excel文档

Seb*_*ien 10 c# oledb datatable excel

我想知道在Excel中读取单元格的最快方法是什么.我有一个包含50000行的Excel文件,我想知道如何快速阅读它.我只需要阅读第一列并使用oledb连接,它需要15秒.有更快的方法吗?

谢谢

jiv*_*son 8

这是一个依赖于使用Microsoft.Office.Interop.Excel的方法.

请注意:我使用的Excel文件只有一列,数据包含50,000个条目.

1)使用Excel打开文件,将其另存为csv,然后关闭Excel.

2)使用StreamReader快速读取数据.

3)拆分回车换行符上的数据并将其添加到字符串列表中.

4)删除我创建的csv文件.

我使用System.Diagnostics.StopWatch来计算执行时间,该函数运行需要1.5568秒.

public static List<string> ExcelReader( string fileLocation )
{                       
    Microsoft.Office.Interop.Excel.Application excel = new Application();
    Microsoft.Office.Interop.Excel.Workbook workBook =
        excel.Workbooks.Open(fileLocation);
    workBook.SaveAs(
        fileLocation + ".csv",
        Microsoft.Office.Interop.Excel.XlFileFormat.xlCSVWindows
    );
    workBook.Close(true);
    excel.Quit();
    List<string> valueList = null;
    using (StreamReader sr = new StreamReader(fileLocation + ".csv")) {
        string content = sr.ReadToEnd();
        valueList = new List<string>(
            content.Split(
                new string[] {"\r\n"},
                StringSplitOptions.RemoveEmptyEntries
            )
        );
    }
    new FileInfo(fileLocation + ".csv").Delete();
    return valueList;
}
Run Code Online (Sandbox Code Playgroud)

资源:

http://www.codeproject.com/Articles/5123/Opening-and-Navigating-Excel-with-C

如何用C#在回车上拆分字符串?

  • 只是想说谢谢你,大大改善了我的计划 (2认同)

Fre*_*cer 2

OLEDB总是需要更多的时间。

SQL Server 2005/2008 将使其更快。

对于 OLEDB 连接,每秒需要 7 条记录,而

对于 SQLServer ,每秒需要 70 条记录。

读取逗号分隔的文件不需要太多时间,但插入数据需要时间。

我确实经历过这件事。

  • 这有什么帮助?OP说他们想导入CSV而不是与SQL Server进行比较? (2认同)