用OLEDB方法将Excel导入到datatable

该方法在导入xlsx文件的时候,如果提示“未在本地计算机上注册“Microsoft.ACE.OLEDB.12.0”提供程序”,需要额外AccessDatabaseEngine.exe,下载链接http://download.microsoft.com/download/7/0/3/703ffbcb-dc0c-4e19-b0da-1463960fdcdb/AccessDatabaseEngine.exe,该链接是2007版本的,比较通用。

另外,注意引用命名空间

using System.Data;
using System.Data.SqlClient;
using System.Data.OleDb;
using Microsoft.Win32;
using System.Windows;
using System;

        public DataTable ImportFromExcel()
        {
            DataSet ds = new DataSet();
            DataTable dt = new DataTable();
            OpenFileDialog ofd = new OpenFileDialog(); //新建一个“打开文件对话框”的实例
            ofd.Title = "导入Excel文件"; //设置对话框的标题
            ofd.Filter = "Excel文件(*.xls,*.xlsx)|*.xls;*.xlsx|All files(*.*)|*.*"; //设置文件筛选器
            string strConn = "";
            OleDbConnection conn = new OleDbConnection();
            if (ofd.ShowDialog() == true)  //打开对话框
            {
                if (System.IO.Path.GetExtension(ofd.FileName).ToLower() == ".xls") //如果选择的是xls文件,就用“=Microsoft.Jet.OLEDB.4.0”的连接字符串;如果是xlsx文件,就用“Microsoft.ACE.OLEDB.12.0”的连接字符串
                {
                    strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + ofd.FileName + ";Extended properties=Excel 8.0;";
                }
                else strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + ofd.FileName + ";Extended properties='Excel 12.0;HDR=Yes;IMEX=1;'";
            }
            conn.ConnectionString = strConn;
            if (System.IO.Path.GetExtension(ofd.FileName).ToLower().Contains(".xls"))
            {
                try
                {
                    if (conn.State == ConnectionState.Closed)
                    { conn.Open(); }
                    DataTable dtSheetName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" }); //获取Excel里sheet的列表
                    for (int i = 0; i < dtSheetName.Rows.Count; i++) //遍历所有的sheet
                    {
                        dt.TableName = "table" + i.ToString(); //设置dt的表名
                        string SheetName = dtSheetName.Rows[i]["TABLE_NAME"].ToString();
                        OleDbDataAdapter oleda = new OleDbDataAdapter("select * from [" + SheetName + "]", conn); //从名为SheetName的sheet获取表格
                        oleda.Fill(dt); //填充dt
                        ds.Tables.Add(dt); //将dt添加到ds
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
                finally
                {
                    conn.Close();
                }
            }
            return ds.Tables[0]; //返回一个需要的Table

 

你可能感兴趣的:(Oledb,Excel,C#,导入,DataTable)