匯出資料版本2 ,個人精簡了一下方法,並且通過測試,可是點擊取消的時候還沒弄清楚,親,等待哈。。。
引用:
//串連資料庫 ---全域
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Loginthree"].ToString());
/// <summary> /// 匯出資料按鈕 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button2_Click(object sender, EventArgs e) { //需要列印的資料 string sqlall = "select * from Student"; DataTable dat = testone(sqlall); printAll(dat); }testone()方法:
/// <summary> /// 擷取資料集返回資料庫中的資料 /// </summary> /// <param name="sql"></param> /// <returns>DataTable</returns> private DataTable testone(string sqlall) { try { conn.Open(); dapter = new SqlDataAdapter(sqlall,conn); //自動產生單表命令,用於將對 DataSet 所做的更改與關聯的 SQL Server 資料庫的更改相協調。無法繼承此類。 SqlCommandBuilder scb = new SqlCommandBuilder(dapter); ds = new DataSet(); dapter.Fill(ds);// dapter.Fill(ds, "class");//DataTable customerTable = dtc["Product"]; return ds.Tables[0]; } catch(Exception e) { Console.WriteLine("{0} Exception caught.", e); } finally { conn.Close(); } return null ; }printAll方法:
/// <summary> /// 匯出excel 方法一 /// </summary> /// <param name="dt"></param> public void printAll(System.Data.DataTable dt) { //匯出到execl //沒有資料的話就不往下執行 if (dt.Rows.Count == 0) return; //執行個體化一個Excel.Application對象 Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application(); // Excel.Application excel = new Excel.Application(); //新增加一個活頁簿,Workbook是直接儲存,不會彈出儲存對話方塊,加上Application會彈出儲存對話方塊,值為false會報錯 Microsoft.Office.Interop.Excel.Workbook xls_book = excel.Workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet); excel.Visible = true; try { //讓後台執行設定為不可見,為true的話會看到開啟一個Excel,然後資料在往裡寫 excel.Visible = false; //產生Excel中列頭名稱 for (int i = 0; i < dt.Columns.Count; i++) { excel.Cells[1, i + 1] = dagvtwo.Columns[i].HeaderText;//輸出DataGridView列頭名 } //把DataGridView當前頁的資料儲存在Excel中 if (dt.Rows.Count > 0) { for (int i = 0; i < dt.Rows.Count; i++) { for (int j = 0; j < dt.Columns.Count; j++) { string str = dt.Rows[i][j].ToString(); excel.Cells[i + 2, j + 1] = "'" + str; } } } //設定禁止彈出儲存和覆蓋的詢問提示框 excel.DisplayAlerts = false; excel.AlertBeforeOverwriting = false; //儲存活頁簿,值為false會報錯 excel.Application.Workbooks.Add(true).Save(); //儲存excel檔案 excel.Save("D:\\KKHMD.xls"); } catch (Exception ex) { MessageBox.Show(ex.Message, "錯誤提示"); } finally { //確保Excel進程關閉 excel.Quit(); excel = null; } }