最近,在做CS端數據導出到Excel中時網上找了很多代碼感覺都不是自己想要的,通過自己的整理歸納得到一個比較通用的方法,就給大家分享一下;
該方法需要用到兩個參數(即對象),一個 DataGridView對象 另外一個是我自己添加的一個進度條的對象,這樣導出數據的時候會出現一個進度條,廢話就不多說了,直接上源碼,大家有什么想法可以留言一起討論。
第一種方式:
public static bool OutToExcelFromDataGridView(string title, DataGridView dgv, bool isShowExcel) { int titleColumnSpan = 0;//標題的跨列數 string fileName = "";//保存的excel文件名 int columnIndex = 1;//列索引 if (dgv.Rows.Count == 0) return false; /*保存對話框*/ SaveFileDialog sfd = new SaveFileDialog(); sfd.Filter = "導出Excel(*.xls)|*.xlsx"; sfd.FileName = title + DateTime.Now.ToString("yyyyMMddhhmmss"); if (sfd.ShowDialog() == DialogResult.OK) { fileName = sfd.FileName; /*建立Excel對象*/ Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application(); if (excel == null) { MessageBox.Show("無法創建Excel對象,可能您的計算機未安裝Excel!"); return false; } try { excel.Application.Workbooks.Add(true); excel.Visible = isShowExcel; /*分析標題的跨列數*/ foreach (DataGridViewColumn column in dgv.Columns) { if (column.Visible == true) titleColumnSpan++; } /*合並標題單元格*/ Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)excel.ActiveSheet; //worksheet.get_Range("A1", "C10").Merge(); worksheet.get_Range(worksheet.Cells[1, 1] as Range, worksheet.Cells[1, titleColumnSpan] as Range).Merge(); /*生成標題*/ excel.Cells[1, 1] = title; (excel.Cells[1, 1] as Range).HorizontalAlignment = XlHAlign.xlHAlignCenter;//標題居中 //生成字段名稱 columnIndex = 1; for (int i = 0; i < dgv.ColumnCount; i++) { if (dgv.Columns[i].Visible == true && dgv.Columns[i].HeaderText != "刪除") { excel.Cells[2, columnIndex] = dgv.Columns[i].HeaderText; (excel.Cells[2, columnIndex] as Range).HorizontalAlignment = XlHAlign.xlHAlignCenter;//字段居中 columnIndex++; } } //填充數據 for (int i = 0; i < dgv.RowCount; i++) { columnIndex = 1; for (int j = 0; j < dgv.ColumnCount; j++) { if (dgv.Columns[j].Visible == true && dgv.Columns[j].HeaderText != "刪除") { if (dgv[j, i].ValueType == typeof(string)) { excel.Cells[i + 3, columnIndex] = "'" + dgv[j, i].Value.ToString(); } else { excel.Cells[i + 3, columnIndex] = dgv[j, i].Value.ToString(); } (excel.Cells[i + 3, columnIndex] as Range).HorizontalAlignment = XlHAlign.xlHAlignLeft;//字段居中 columnIndex++; } } } worksheet.SaveAs(fileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); } catch { } finally { excel.Quit(); excel = null; GC.Collect(); } KillProcess("Excel"); return true; } else { return false; } } private static void KillProcess(string processName)//殺死與Excel相關的進程 { System.Diagnostics.Process myproc = new System.Diagnostics.Process();//得到所有打開的進程 try { foreach (System.Diagnostics.Process thisproc in System.Diagnostics.Process.GetProcessesByName(processName)) { if (!thisproc.CloseMainWindow()) { thisproc.Kill(); } } } catch (Exception Exc) { throw new Exception("", Exc); } }
第二種方式
public static void DataGridViewToExcel(DataGridView dgv,ProgressBar tempProgressBar) { #region 驗證可操作性 //申明保存對話框 SaveFileDialog dlg = new SaveFileDialog(); //默然文件后綴 dlg.DefaultExt = "xlsx"; //文件后綴列表 dlg.Filter = "EXCEL文件(*.XLS)|*.xlsx"; //默然路徑是系統當前路徑 dlg.InitialDirectory = Directory.GetCurrentDirectory(); //打開保存對話框 if (dlg.ShowDialog() == DialogResult.Cancel) return; //返回文件路徑 string fileNameString = dlg.FileName; //驗證strFileName是否為空或值無效 if (fileNameString.Trim() == " ") { return; } //定義表格內數據的行數和列數 int rowscount = dgv.Rows.Count; int colscount = dgv.Columns.Count; //行數必須大於0 if (rowscount <= 0) { MessageBox.Show("沒有數據可供保存 ", "提示 ", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } //列數必須大於0 if (colscount <= 0) { MessageBox.Show("沒有數據可供保存 ", "提示 ", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } //行數不可以大於65536 if (rowscount > 65536) { MessageBox.Show("數據記錄數太多(最多不能超過65536條),不能保存 ", "提示 ", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } //列數不可以大於255 if (colscount > 255) { MessageBox.Show("數據記錄行數太多,不能保存 ", "提示 ", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } //驗證以fileNameString命名的文件是否存在,如果存在刪除它 FileInfo file = new FileInfo(fileNameString); if (file.Exists) { try { file.Delete(); } catch (Exception error) { MessageBox.Show(error.Message, "刪除失敗 ", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } } #endregion Microsoft.Office.Interop.Excel.Application objExcel = null; Microsoft.Office.Interop.Excel.Workbook objWorkbook = null; Microsoft.Office.Interop.Excel.Worksheet objsheet = null; try { //申明對象 objExcel = new Microsoft.Office.Interop.Excel.Application(); objWorkbook = objExcel.Workbooks.Add(Missing.Value); objsheet = (Microsoft.Office.Interop.Excel.Worksheet)objWorkbook.ActiveSheet; //設置EXCEL不可見 objExcel.Visible = false; //向Excel中寫入表格的表頭 int displayColumnsCount = 1; for (int i = 0; i <= dgv.ColumnCount - 1; i++) { if (dgv.Columns[i].Visible == true&& dgv.Columns[i].HeaderText.Trim()!="刪除" && dgv.Columns[i].HeaderText.Trim() !="") { objExcel.Cells[1, displayColumnsCount] = dgv.Columns[i].HeaderText.Trim(); displayColumnsCount++; } } //設置進度條 tempProgressBar.Refresh(); tempProgressBar.Visible = true; tempProgressBar.Minimum =1; tempProgressBar.Maximum =dgv.RowCount; tempProgressBar.Step = 1; //向Excel中逐行逐列寫入表格中的數據 for (int row = 0; row <= dgv.RowCount - 1; row++) { tempProgressBar.PerformStep(); displayColumnsCount = 1; for (int col = 0; col < colscount; col++) { if (dgv.Columns[col].Visible == true&& dgv.Columns[col].HeaderText!="刪除" && dgv.Columns[col].HeaderText.Trim() != "") { try { string Val = dgv.Rows[row].Cells[col].Value.ToString().Trim(); if (Val.Length >8) { Val = "'" + Val;//加單引號 } objExcel.Cells[row + 2, displayColumnsCount] = Val; displayColumnsCount++; } catch (Exception) { } } } } //隱藏進度條 tempProgressBar.Visible = false; //保存文件 objWorkbook.SaveAs(fileNameString, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlShared, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value); } catch (Exception error) { MessageBox.Show(error.Message, "警告 ", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } finally { //關閉Excel應用 if (objWorkbook != null) objWorkbook.Close(Missing.Value, Missing.Value, Missing.Value); if (objExcel.Workbooks != null) objExcel.Workbooks.Close(); if (objExcel != null) objExcel.Quit(); objsheet = null; objWorkbook = null; objExcel = null; } MessageBox.Show(fileNameString + "導出完畢! ", "提示 ", MessageBoxButtons.OK, MessageBoxIcon.Information); }
個人推薦第一種,經過測試第一種也可以,但是比較麻煩一些,第二種通俗簡單,推薦使用;
根據個人喜好的選擇吧,歡迎大神前來提意見;