private void btnShow_Click(object sender, EventArgs e) { OpenFileDialog fd = new OpenFileDialog();//首先根據(jù)打開文件對話框,,選擇excel表格 ofd.Filter = "表格|*.xls";//打開文件對話框篩選器 string strPath;//文件完整的路徑名 if (ofd.ShowDialog() == DialogResult.OK) { try { strPath = ofd.FileName; string strCon = "provider=microsoft.jet.oledb.4.0;data source=" + strPath + ";extended properties=excel 8.0";//關鍵是紅色區(qū)域 OleDbConnection Con = new OleDbConnection(strCon);//建立連接 string strSql = "select * from [Sheet1$]";//表名的寫法也應注意不同,對應的excel表為sheet1,,在這里要在其后加美元符號$,,并用中括號 OleDbCommand Cmd = new OleDbCommand(strSql, Con);//建立要執(zhí)行的命令 OleDbDataAdapter da = new OleDbDataAdapter(Cmd);//建立數(shù)據(jù)適配器 DataSet ds = new DataSet();//新建數(shù)據(jù)集 da.Fill(ds, "shyman");//把數(shù)據(jù)適配器中的數(shù)據(jù)讀到數(shù)據(jù)集中的一個表中(此處表名為shyman,可以任取表名) //指定datagridview1的數(shù)據(jù)源為數(shù)據(jù)集ds的第一張表(也就是shyman表),,也可以寫ds.Table["shyman"] dataGridView1.DataSource = ds.Tables[0]; } catch (Exception ex) { MessageBox.Show(ex.Message);//捕捉異常 } } } 運行結(jié)果如下: 2.導出DataGridView中的數(shù)據(jù)到Excel的方法: public void ToExcel(DataGridView dataGridView1) { try { //沒有數(shù)據(jù)的話就不往下執(zhí)行 if (dataGridView1.Rows.Count == 0) return; //實例化一個Excel.Application對象 Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application(); //讓后臺執(zhí)行設置為不可見,,為true的話會看到打開一個Excel,然后數(shù)據(jù)在往里寫 excel.Visible = true; //新增加一個工作簿,,Workbook是直接保存,,不會彈出保存對話框,加上Application會彈出保存對話框,,值為false會報錯 excel.Application.Workbooks.Add(true); //生成Excel中列頭名稱 for (int i = 0; i < dataGridView1.Columns.Count; i++) { if (this.dataGridView1.Columns[i].Visible==true) { excel.Cells[1, i + 1] = dataGridView1.Columns[i].HeaderText; } } //把DataGridView當前頁的數(shù)據(jù)保存在Excel中 for (int i = 0; i < dataGridView1.Rows.Count - 1; i++) { System.Windows.Forms.Application.DoEvents(); for (int j = 0; j < dataGridView1.Columns.Count; j++) { if (this.dataGridView1.Columns[j].Visible==true) { if (dataGridView1[j, i].ValueType == typeof(string)) { excel.Cells[i + 2, j + 1] = "'" + dataGridView1[j, i].Value.ToString(); } else { excel.Cells[i + 2, j + 1] = dataGridView1[j, i].Value.ToString(); } } } } //設置禁止彈出保存和覆蓋的詢問提示框 excel.DisplayAlerts = false; excel.AlertBeforeOverwriting = false; //保存工作簿 excel.Application.Workbooks.Add(true).Save(); //保存excel文件 excel.Save("D:" + "\\KKHMD.xls"); //確保Excel進程關閉 excel.Quit(); excel = null; GC.Collect();//如果不使用這條語句會導致excel進程無法正常退出,,使用后正常退出 MessageBox.Show(this,"文件已經(jīng)成功導出!","信息提示"); } catch (Exception ex) { MessageBox.Show(ex.Message, "錯誤提示"); } }
|
|