您的位置:首页 > 其它

使用OLEDB读取Excel文件

2011-03-29 17:15 369 查看
以前对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();
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: