以前对Excel操作,使用的Microsoft.Office.Interop.Excel来操作Excel,需要启动一个excel进程,速度慢。
最近发现可以使用OLEDB配合Dataset的方法来操作Excel,和操作数据库一样,简单快速:
using System; using System.Collections.Generic; using System.Text; using System.Data; using System.Data.OleDb; namespace ExcelTest { class Program { static void Main(string[] args) { string source = "Provider=Microsoft.Ace.OLEDB.12.0;Data Source='1.xlsx';Extended Properties='Excel 12.0;HDR=yes;IMEX=1'"; OleDbConnection conn = new OleDbConnection(source); try { conn.Open(); string select = "SELECT * FROM [Sheet1$]"; OleDbDataAdapter readCommand = new OleDbDataAdapter(select, conn); DataSet readData = new DataSet("Data"); readCommand.Fill(readData); foreach (DataTable dt in readData.Tables) { foreach (DataRow dr in dt.Rows) { foreach (DataColumn dc in dr.Table.Columns) { string cell = dr[dc].ToString(); Console.Write("[" + dc.ColumnName + ": " + dr[dc] + "] "); } Console.WriteLine(); } } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } finally { conn.Close(); Console.ReadLine(); } } } }
作者:Harry Huang
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利.