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

相关文章:

  • 2021-09-27
  • 2022-02-14
  • 2021-12-16
  • 2022-12-23
  • 2022-01-20
  • 2022-12-23
  • 2021-05-20
  • 2018-06-27
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-05-30
  • 2022-12-23
  • 2022-01-06
  • 2022-01-07
相关资源
相似解决方案