標籤: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檔案匯入操作