C# 資料表匯出Excel表格
阿新 • • 發佈:2018-12-15
private void button5_Click(object sender, EventArgs e) { datatable dt=new datatable(); //需要轉換的資料表 ExportToExcel(dt,"excel表格名"); } ///datatable匯出Excel表格函式 public void ExportToExcel(DataTable dt, string saveFileName) { if (dt == null) return; Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application(); if (xlApp == null) { // lblMsg.Text = "無法建立Excel物件,可能您的機子未安裝Excel"; MessageBox.Show("請確保您的電腦已經安裝Excel", "提示資訊", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks; Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet); Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1]; //取得sheet1 Microsoft.Office.Interop.Excel.Range range = null; long totalCount = dt.Rows.Count; long rowRead = 0; float percent = 0; //寫入標題 for (int i = 0; i < dt.Columns.Count; i++) { worksheet.Cells[1, i + 1] = dt.Columns[i].ColumnName; range = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[1, i + 1]; range.Interior.ColorIndex = 15;//背景顏色 range.Font.Bold = true; //粗體 range.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter; //居中 //加邊框 range.BorderAround(Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous, Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin, Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic, null); //range.ColumnWidth = 4.63;//設定列寬 //range.EntireColumn.AutoFit();//自動調整列寬 //r1.EntireRow.AutoFit();//自動調整行高 } //寫入內容 for (int r = 0; r < dt.Rows.Count; r++) { for (int i = 0; i < dt.Columns.Count; i++) { try { worksheet.Cells[r + 2, i + 1] = dt.Rows[r][i]; range = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[r + 2, i + 1]; range.Font.Size = 9; //字型大小 //加邊框 range.BorderAround(Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous, Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin, Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic, null); range.EntireColumn.AutoFit(); //自動調整列寬 } catch (Exception) { } } rowRead++; percent = ((float)(100 * rowRead)) / totalCount; Application.DoEvents(); } range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideHorizontal].Weight = Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin; if (dt.Columns.Count > 1) { range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideVertical].Weight = Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin; } try { workbook.Saved = true; SaveFileDialog SaveFile = new SaveFileDialog(); SaveFile.FileName = saveFileName; //SaveFile.Filter = "Miscrosoft Office Excel 97-2003 工作表|*.xls|所有檔案(*.*)|*.*"; SaveFile.Filter = "Miscrosoft Office Excel 97-2003 工作表|*.xls|Excel 工作簿|*.xlsx|所有檔案(*.*)|*.*"; SaveFile.RestoreDirectory = true; if (SaveFile.ShowDialog() == DialogResult.OK) { workbook.SaveCopyAs(SaveFile.FileName); MessageBox.Show("匯出資料成功!", "系統資訊", MessageBoxButtons.OK, MessageBoxIcon.Information); } } catch (Exception ex) { //MessageBox.Show("匯出檔案時出錯,檔案可能正被開啟!", "系統資訊"); MessageBox.Show(ex.Message.ToString()); } //在關閉時會卡死程式,暫未測試原因 //try //{ // workbooks.Close(); // if (xlApp != null) // { // xlApp.Workbooks.Close(); // xlApp.Quit(); // int generation = GC.GetGeneration(xlApp); // System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp); // xlApp = null; // GC.Collect(generation); // } // GC.Collect(); //強行銷燬 //} //catch (Exception ex) { // MessageBox.Show("coles error!!!"); //} //#region 強行殺死最近開啟的Excel程序 //System.Diagnostics.Process[] excelProc = System.Diagnostics.Process.GetProcessesByName("EXCEL"); //DateTime startTime = new DateTime(); //int m = 0; //int killId = 0; //for (m = 0; m < excelProc.Length; m++) //{ // if (startTime < excelProc[m].StartTime) // { // startTime = excelProc[m].StartTime; // killId = m; // } //} //try //{ // if (killId > 0 && excelProc[killId].HasExited == false) // { // excelProc[killId].Kill(); // } //} //catch (Exception ex) //{ //} //#endregion }