C# Excel檔案匯入操作

來源:互聯網
上載者:User

標籤:c#   excel   匯入excel   

Excel檔案匯出的操作我們經常用到,但是講一個Excel文檔匯入並顯示到介面還是第一次用到。

下面簡單介紹下在C#下如何進行Excel檔案的匯入操作。

首先添加兩個引用

using System.IO;
using System.Data.OleDb;

添加控制項openFileDialog

然後我們需要配置Excel的OleDb連接字串

<span style="font-size:14px;">public const string OledbConnString = "Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = {0};Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'"; //Excel的 OleDb 連接字串</span>

選擇一個Excel檔案
        /// <summary>        /// 選擇EXCEL        /// </summary>        private void btn_BrowserExcel_Click(object sender, EventArgs e)        {            DialogResult dr = this.openFileDialog1.ShowDialog();            if (DialogResult.OK == dr) //判斷是否選擇檔案            {                this.txtPath.Text = this.openFileDialog1.FileName;                this.btn_Import.Enabled = true;            }        }

執行匯入的操作且綁定資料來源
        /// <summary>        /// 執行匯入操作        /// </summary>        private void btn_Import_Click(object sender, EventArgs e)        {            string path = this.txtPath.Text.Trim();            if (string.IsNullOrEmpty(path))            {                MessageBox.Show("請選擇要匯入的EXCEL檔案。", "資訊");                return;            }            if (!File.Exists(path))  //判斷檔案是否存在            {                MessageBox.Show("資訊", "找不到對應的Excel檔案,請重新選擇。");                this.btn_BrowserExcel.Focus();                return;            }            DataTable excelTbl = this.GetExcelTable(path);  //調用函數擷取Excel中的資訊            if (excelTbl == null)            {                return;            }            DgvImport.DataSource = excelTbl;        }

最核心的功能在這裡:

        /// <summary>        /// 擷取Excel檔案中的資訊,儲存到一個DataTable中        /// </summary>        /// <param name="path">檔案路徑</param>        /// <returns>返回產生的DataTable</returns>        private DataTable GetExcelTable(string path)        {            try            {                //擷取excel資料                DataTable dt1 = new DataTable("excelTable");                string strConn = string.Format(OledbConnString, path);                OleDbConnection conn = new OleDbConnection(strConn);                conn.Open();                DataTable dt = conn.GetSchema("Tables");                //判斷excel的sheet頁數量,查詢第1頁                if (dt.Rows.Count > 0)                {                    string selSqlStr = string.Format("select * from [{0}]", dt.Rows[0]["TABLE_NAME"]);                    OleDbDataAdapter oleDa = new OleDbDataAdapter(selSqlStr, conn);                    oleDa.Fill(dt1);                }                conn.Close();                return dt1;            }            catch (Exception ex)            {                MessageBox.Show("Excel轉換DataTable出錯:" + ex.Message);                return null;            }        }
      :

                                        

       看到這裡大家肯定會有種似曾相識的感覺,最上面配置連接字串,這裡的GetExcelTable方法,開啟串連,查詢語句,執行命令,填充table,關閉串連。不就是從資料庫查詢資料過程的翻版嗎?

       果然知識都是相通的。


C# Excel檔案匯入操作

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.