使用OLEDB读取Excel文件
以前对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 发表于 2011-03-29 17:15 原文链接
Tag 使用oledb读取excel文件
推荐.NET配套的通用数据层ORM框架:CYQ.Data 通用数据层框架