winfrom導入excel內容,要求能夠excel中多個工作簿的內容。代碼如下:
#region 導入excel數據 private void button2_Click(object sender, EventArgs e) { OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.Filter = "表格文件 (*.xls)|*.xls"; openFileDialog.RestoreDirectory = true; openFileDialog.FilterIndex = 1; if (openFileDialog.ShowDialog() == DialogResult.OK) { Import(openFileDialog.FileName); } } /// <summary> /// 導入excel數據 /// </summary> /// <param name="filePath"></param> /// <returns></returns> public static bool Import(string filePath) { try { //Excel就好比一個數據源一般使用 //這里可以根據判斷excel文件是03的還是07的,然后寫相應的連接字符串 string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + filePath + ";" + "Extended Properties=Excel 8.0;"; OleDbConnection con = new OleDbConnection(strConn); con.Open(); string[] names = GetExcelSheetNames(con); if (names.Length > 0) { foreach (string name in names) { OleDbCommand cmd = con.CreateCommand(); cmd.CommandText = string.Format(" select * from [{0}]", name);//[sheetName]要如此格式 OleDbDataReader odr = cmd.ExecuteReader(); while (odr.Read()) { if (odr[0].ToString() == "序號")//過濾列頭 按你的實際Excel文件 continue; //數據庫添加操作 /*進行非法值的判斷 * 添加數據到數據表中 * 添加數據時引用事物機制,避免部分數據提交 * Add(odr[1].ToString(), odr[2].ToString(), odr[3].ToString());//數據庫添加操作,Add方法自己寫的 * */ } odr.Close(); } } return true; } catch (Exception) { return false; } } /// <summary> /// 查詢表名 /// </summary> /// <param name="con"></param> /// <returns></returns> public static string[] GetExcelSheetNames(OleDbConnection con) { try { System.Data.DataTable dt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new[] { null, null, null, "Table" });//檢索Excel的架構信息 var sheet = new string[dt.Rows.Count]; for (int i = 0, j = dt.Rows.Count; i < j; i++) { //獲取的SheetName是帶了$的 sheet[i] = dt.Rows[i]["TABLE_NAME"].ToString(); } return sheet; } catch { return null; } } //下面這種方法獲取excel Worksheets Name時,提示無法訪問該exceL文件,所以改為上面獲取工作簿名的方式 ///// <summary> ///// 獲得excel sheet所有工作簿名字 ///// </summary> ///// <param name="filePath"></param> ///// <returns></returns> //public static string[] GetExcelSheetNames(string filePath) //{ // Microsoft.Office.Interop.Excel.ApplicationClass excelApp = new Microsoft.Office.Interop.Excel.ApplicationClass(); // Microsoft.Office.Interop.Excel.Workbooks wbs = excelApp.Workbooks; // Microsoft.Office.Interop.Excel.Workbook wb = wbs.Open(filePath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, // Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, // Type.Missing, Type.Missing, Type.Missing, Type.Missing); // int count = wb.Worksheets.Count; // string[] names = new string[count]; // for (int i = 1; i <= count; i++) // { // names[i - 1] = ((Microsoft.Office.Interop.Excel.Worksheet)wb.Worksheets[i]).Name; // } // return names; //} #endregion