C#開發——winform中將Excel資料匯入DataGridView
阿新 • • 發佈:2019-02-02
using System; using System.Data; using System.Data.OleDb; using System.Windows.Forms; namespace ExcelToGridview { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btnopenfile_Click(object sender, EventArgs e) { try { //獲取Excel檔案路徑和名稱 OpenFileDialog odXls = new OpenFileDialog(); //指定相應的開啟文件的目錄 AppDomain.CurrentDomain.BaseDirectory定位到Debug目錄,再根據實際情況進行目錄調整 string folderPath = AppDomain.CurrentDomain.BaseDirectory + @"databackup\"; odXls.InitialDirectory = folderPath; // 設定檔案格式 odXls.Filter = "Excel files office2003(*.xls)|*.xls|Excel office2010(*.xlsx)|*.xlsx|All files (*.*)|*.*"; //openFileDialog1.Filter = "圖片檔案(*.jpg)|*.jpg|(*.JPEG)|*.jpeg|(*.PNG)|*.png"; odXls.FilterIndex = 2; odXls.RestoreDirectory = true; if (odXls.ShowDialog() == DialogResult.OK) { this.txtFilePath.Text = odXls.FileName; this.txtFilePath.ReadOnly = true; string sConnString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source={0};" + "Extended Properties='Excel 8.0;HDR=NO;IMEX=1';", odXls.FileName); if ((System.IO.Path.GetExtension(txtFilePath.Text.Trim())).ToLower() == ".xls") { sConnString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "data source=" + odXls.FileName + ";Extended Properties=Excel 5.0;Persist Security Info=False"; //sConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + txtFilePath.Text.Trim() + ";Extended Properties=\"Excel 8.0;HDR=" + strHead + ";IMEX=1\""; } using (OleDbConnection oleDbConn = new OleDbConnection(sConnString)) { oleDbConn.Open(); DataTable dt = oleDbConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" }); //判斷是否cmb中已有資料,有則清空 if (cmbtablename.Items.Count > 0) { cmbtablename.DataSource = null; cmbtablename.Items.Clear(); } //遍歷dt的rows得到所有的TABLE_NAME,並Add到cmb中 foreach (DataRow dr in dt.Rows) { cmbtablename.Items.Add((String)dr["TABLE_NAME"]); } if (cmbtablename.Items.Count > 0) { cmbtablename.SelectedIndex = 0; } //載入Excel檔案資料按鈕 this.btnshow.Enabled = true; } } } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void btnshow_Click(object sender, EventArgs e) { #region 讀取相應的表名的Excel檔案中資料到當前DataGridview中顯示 OleDbConnection ole = null; OleDbDataAdapter da = null; DataTable dt = null; string strConn = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source={0};" + "Extended Properties='Excel 8.0;HDR=NO;IMEX=1';", txtFilePath.Text.Trim()); if ((System.IO.Path.GetExtension(txtFilePath.Text.Trim())).ToLower() == ".xls") { strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "data source=" + txtFilePath.Text.Trim() + ";Extended Properties=Excel 5.0;Persist Security Info=False"; //sConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + txtFilePath.Text.Trim() + ";Extended Properties=\"Excel 8.0;HDR=" + strHead + ";IMEX=1\""; } string sTableName = cmbtablename.Text.Trim(); string strExcel = "select * from [" + sTableName + "]"; try { ole = new OleDbConnection(strConn); ole.Open(); da = new OleDbDataAdapter(strExcel, ole); dt = new DataTable(); da.Fill(dt); this.dgvdata.DataSource = dt; //因為生成Excel的時候第一行是標題,所以要做如下操作: //1.修改DataGridView列頭的名字, //2.資料列表中刪除第一行 for (int i = 0; i < dt.Columns.Count; i++) { //dgvdata.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells; //dgvdata.Columns[i].Name = dt.Columns[i].ColumnName; dgvdata.Columns[i].HeaderCell.Value = dt.Rows[0][i].ToString();//c# winform 用程式碼修改DataGridView列頭的名字,設定列名,修改列名 } //DataGridView刪除行 dgvdata.Rows.Remove(dgvdata.Rows[0]);//刪除第一行 //dgvdata.Rows.Remove(dgvdata.CurrentRow);//刪除當前游標所在行 //dgvdata.Rows.Remove(dgvdata.Rows[dgvdata.Rows.Count - 1]);//刪除最後一行 //dgvdata.Rows.Clear();//刪除所有行 ole.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { if (ole != null) ole.Close(); } #endregion }