C#中將DataGridView中查詢出來的資料使用DataTable匯出為Excel表格(通過NPOI)
阿新 • • 發佈:2019-01-28
1.首先在當前專案中新增引用NPOI.dll
2.在專案中新增類ExportExcel.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Collections; using System.Data; using System.Windows.Forms; using NPOI; using NPOI.Util; using NPOI.HPSF; using NPOI.HSSF.UserModel; using NPOI.HSSF.Util; using NPOI.POIFS; using NPOI.POIFS.FileSystem; using NPOI.SS.Util; using NPOI.SS.UserModel; namespace 測試 { public class ExportExcel { static IWorkbook hssfworkbook; #region 匯出Excel /// <summary> /// 使用DataTable匯出資料 /// </summary> /// <param name="dt">資料</param> /// <param name="FileName">檔名</param> /// <param name="msg">提示訊息</param> public static void DtToExcel(DataTable dt, string FileName) { try { if (dt != null && dt.Rows.Count > 0) { SaveFileDialog dlg = new SaveFileDialog();//申明儲存對話方塊 dlg.Filter = "Excel檔案|*.xls"; dlg.FileName = FileName;//預設檔名稱 if (dlg.ShowDialog() == DialogResult.Cancel) return; dlg.InitialDirectory = Directory.GetCurrentDirectory();//返回檔案路徑 string filename = dlg.FileName;//輸出的檔名稱 if (filename.Trim() == " ")//驗證strFileName是否為空或值無效 { return; } hssfworkbook = new HSSFWorkbook(); ISheet sheet = hssfworkbook.CreateSheet("Sheet1"); int colscount = dt.Columns.Count;//定義表格內資料的列數 ArrayList arr = new ArrayList();//儲存頭資訊 ICellStyle cstyle = hssfworkbook.CreateCellStyle(); IRow rowHeader = sheet.CreateRow(0);//建立列頭資料 int displayColumnsCount = 0;//用於處理隱藏列頭不被顯示 HSSFFont hssffont = hssfworkbook.CreateFont() as HSSFFont; hssffont.FontHeightInPoints = 11; //設定單元格邊框 for (int i = 0; i < dt.Columns.Count; i++)//生成表頭資訊 { ICell cell = rowHeader.CreateCell(displayColumnsCount); cell.SetCellValue(dt.Columns[i].ToString()); sheet.SetColumnWidth(displayColumnsCount, 17 * 256); displayColumnsCount++; arr.Add(dt.Columns[i].ToString()); } for (int i = 0; i < dt.Rows.Count; i++) { IRow irow = sheet.CreateRow(i + 1); for (int j = 0; j < dt.Columns.Count - 1; j++) { ICell cell = irow.CreateCell(j); cell.SetCellValue(dt.Rows[i][j].ToString()); } } using (Stream stream = File.OpenWrite(filename)) { hssfworkbook.Write(stream); MessageBox.Show(filename + "\n\n匯出完畢! ", "提示 ", MessageBoxButtons.OK, MessageBoxIcon.Information); } } else { MessageBox.Show("沒有資料可供匯出", "提示"); } } catch { MessageBox.Show("操作失敗", "提示"); } } #endregion } }
3.新增一個button按鈕btExport,新增事件btExport_Click
private void btExport_Click(object sender, EventArgs e) { if (this.dgvdata.Rows.Count == 0) { MessageBox.Show("未能查詢到資料!!!","提示"); return; } ExportExcel.DtToExcel(dt, "預設檔名"); }
4.除錯程式,點選button按鈕,可以匯出資料
NPOI下載地址: