博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

使用OLEDB读取Excel文件

Posted on 2011-03-29 17:15  Harry Huang  阅读(3363)  评论(2编辑  收藏  举报

以前对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();
            }
        }
    }
}