阅读一个大的Excel文件

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

谢谢

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

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

1)用Excel打开文件,保存为csv,closuresExcel。

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

3)在回车换行上拆分数据并将其添加到string列表中。

4)删除我创build的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; } 

资源:

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

如何拆分string回车与C#?

你可以把你的代码读取使用OLEDB提供商50000logging。 我试过这样做,花费4-5秒钟读取3列的50000条logging。 我做了以下的方式,只是看看,它可能会帮助你。 🙂

  // txtPath.Text is the path to the excel file string conString = @"Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + txtPath.Text + ";" + "Extended Properties=" + "\"" + "Excel 12.0;HDR=YES;" + "\""; OleDbConnection oleCon = new OleDbConnection(conString); OleDbCommand oleCmd = new OleDbCommand("SELECT field1, field2, field3 FROM [Sheet1$]", oleCon); DataTable dt = new DataTable(); oleCon.Open(); dt.Load(oleCmd.ExecuteReader()); oleCon.Close(); 

如果你可以把你的代码放在这里,那么我可以尝试纠正。 🙂

OLEDB将总是需要更多的时间。

SQL Server 2005/2008将使其更快。

对于OLEDB连接,每秒需要7条logging

对于SQLServer,每秒钟需要70条logging。

阅读逗号分隔文件需要的时间不长,但是需要时间来插入数据。

我从字面上经历过这件事情。

你只是想读一个文件中的数字列表? 它必须在Excel中吗? 是一些非技术人员更新名单? 如果您想从单列中读取50,000个数字到内存中的列表中,只需将单元格复制到文本文件并使用TextReader读取即可。 这将是瞬间的。

 List<string> ReadFile(string path) { TextReader tr = new StreamReader(path); string line; List<string> lines = new List<string>(); while((line=tr.ReadLine())!=null) { //if this was a CSV, you could string.split(',') here lines.add(line); } return lines; } 

我面对同样的事情,我在办公室开发中心读:

http://social.msdn.microsoft.com/Forums/office/en-US/418ada31-8748-48d2-858b-d177326daa76/export-to-excel-open-xml-sdk-vs-microsoftofficeinteropexcel?forum=oxmlsdk

你有两个操作Excel文件的select:

  • 使用Excel.Application作为代码执行的附加层的Microsoft.Office.Interop.Excel
  • Open XML SDK,允许开发人员直接使用closures的文件

两者之间没有太大的区别,但在您的情况下,性能是一个问题,您应该使用Open XML SDK,可能会更快一些,在处理之前不需要太多时间打开大文件。 你也可以在上面的链接中阅读,我引用:

自动化办公室不受支持。 办公室的申请并不是在没有人力监督的情况下运作的,而且有一个“挂”

在这个链接中提供了学习open xml sdk的好的开始: http : //msdn.microsoft.com/en-us/library/office/gg575571.aspx