一、點擊導入按鈕,彈出文件選擇框
這個方法的使用要引用下面兩個命名空間:
using System.Windows.Forms;
using DevExpress.XtraEditors;
1 private void button1_Click(object sender, EventArgs e) 2 { 3 OpenFileDialog ofd = new OpenFileDialog(); 4 ofd.Title = "選擇文件"; 5 ofd.Filter = "Microsoft Excel文件|*.xls;*.xlsx"; 6 ofd.FilterIndex = 1; 7 ofd.DefaultExt = "xls"; 8 if (ofd.ShowDialog() == DialogResult.OK) 9 { 10 if (!ofd.SafeFileName.EndsWith(".xls") && !ofd.SafeFileName.EndsWith(".xlsx")) 11 { 12 XtraMessageBox.Show("請選擇Excel文件","文件解析失敗!",MessageBoxButtons.OK,MessageBoxIcon.Error); 13 return; 14 } 15 if (!ofd.CheckFileExists) 16 { 17 XtraMessageBox.Show("指定的文件不存在","請檢查!",MessageBoxButtons.OK,MessageBoxIcon.Error); 18 return; 19 } 20 //DataTable dt = NpoiOperExcel.ExcelToDataTable(ofd.FileName,true); 21 DataSet ds = NpoiOperExcel.DsExcel(ofd.FileName); 22 } 23 }
21行使用的方法,讀取excel表格
1 public static DataSet DsExcel(string filePath) 2 { 3 string str = "Provider = Microsoft.Jet.OLEDB.4.0; Data Source = " + filePath + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\"";//智能讀取2003版本 4 OleDbConnection con = new OleDbConnection(str); 5 try 6 { 7 con.Open(); 8 DataTable dt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null); 9 string tablename = "", sql = ""; 10 w_import_select_table wi = new w_import_select_table();//創建的一個窗體,用於選擇工作表格 11 wi.dt = dt; 12 if (wi.ShowDialog() != DialogResult.Yes) 13 { 14 return null; 15 } 16 tablename = wi.listBox1.Text.Trim(); 17 sql = "select * from [" + tablename + "]"; 18 OleDbDataAdapter da = new OleDbDataAdapter(sql, con); 19 DataSet ds = new DataSet(); 20 da.Fill(ds, tablename); 21 return ds; 22 } 23 catch (Exception ex) 24 { 25 XtraMessageBox.Show(ex.ToString()); 26 return null; 27 } 28 finally 29 { 30 if (con.State == ConnectionState.Open) 31 { 32 con.Close(); 33 } 34 } 35 }
下面就是把table傳到數據庫,使用表類型接收