C# Winform中DataGridView導出為Excel的實現(xiàn)示例
1、前言
話不多說,跟著我的步驟保證你也能成功,下面直接開始!
2、效果展示
導出前
導出后
3、詳細步驟
下面是詳細操作步驟,請跟著我的步伐,一步一步進行操作,保證你能夠導出成功!
3.1 添加NPOI和NPOI.Excel包
首先請請確定你的vs已經(jīng)打開了【解決方案資源管理器】,打開步驟見下圖:
在資源管理器中找到【引用】,然后在【引用】上右鍵選擇【管理程序包】并點擊,如下圖:
在新打開的窗口中點擊【瀏覽】并在搜索框中依次輸入NPOI和NPOI.Excel并進行安裝,安裝按鈕位置如下圖:
待安裝完成再進行下一步
3.2 創(chuàng)建NPOIHelper類
首先在資源管理器中選中你的項目,【右鍵】找到【添加】–>【類】,具體如下圖:
創(chuàng)建一個名字為【NPOIHelper.cs】的類并打開
3.2.1 導入命名空間
復制下面的代碼,覆蓋你自動生成的命名空間
using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms;
3.2.2 插入代碼
將下面的代碼導入到下圖位置:
public class ExcelUtility { /// <summary> /// 將excel導入到datatable /// </summary> /// <param name="filePath">excel路徑</param> /// <param name="isColumnName">第一行是否是列名</param> /// <returns>返回datatable</returns> public static DataTable ExcelToDataTable(string filePath, bool isColumnName) { DataTable dataTable = null; FileStream fs = null; DataColumn column = null; DataRow dataRow = null; IWorkbook workbook = null; ISheet sheet = null; IRow row = null; ICell cell = null; int startRow = 0; try { using (fs = File.OpenRead(filePath)) { // 版本后綴控制 if (filePath.IndexOf(".xlsx") > 0) workbook = new XSSFWorkbook(fs); // 版本后綴控制 else if (filePath.IndexOf(".xls") > 0) workbook = new HSSFWorkbook(fs); if (workbook != null) { sheet = workbook.GetSheetAt(0);//讀取第一個sheet,當然也可以循環(huán)讀取每個sheet dataTable = new DataTable(); if (sheet != null) { int rowCount = sheet.LastRowNum;//總行數(shù) if (rowCount > 0) { IRow firstRow = sheet.GetRow(0);//第一行 int cellCount = firstRow.LastCellNum;//列數(shù) //構建datatable的列 if (isColumnName) { startRow = 1;//如果第一行是列名,則從第二行開始讀取 for (int i = firstRow.FirstCellNum; i < cellCount; ++i) { cell = firstRow.GetCell(i); if (cell != null) { if (cell.StringCellValue != null) { column = new DataColumn(cell.StringCellValue); dataTable.Columns.Add(column); } } } } else { for (int i = firstRow.FirstCellNum; i < cellCount; ++i) { column = new DataColumn("column" + (i + 1)); dataTable.Columns.Add(column); } } //填充行 for (int i = startRow; i <= rowCount; ++i) { row = sheet.GetRow(i); if (row == null) continue; dataRow = dataTable.NewRow(); for (int j = row.FirstCellNum; j < cellCount; ++j) { cell = row.GetCell(j); if (cell == null) { dataRow[j] = ""; } else { //CellType(Unknown = -1,Numeric = 0,String = 1,Formula = 2,Blank = 3,Boolean = 4,Error = 5,) switch (cell.CellType) { case CellType.Blank: dataRow[j] = ""; break; case CellType.Numeric: short format = cell.CellStyle.DataFormat; //對時間格式(2015.12.5、2015/12/5、2015-12-5等)的處理 if (format == 14 || format == 31 || format == 57 || format == 58) dataRow[j] = cell.DateCellValue; else dataRow[j] = cell.NumericCellValue; break; case CellType.String: dataRow[j] = cell.StringCellValue; break; } } } dataTable.Rows.Add(dataRow); } } } } } return dataTable; } catch (Exception) { if (fs != null) { fs.Close(); } return null; } } } public static bool DataTableToExcel(DataTable dt, string txtPath) { bool result = false; IWorkbook workbook = null; FileStream fs = null; IRow row = null; ISheet sheet = null; ICell cell = null; try { if (dt != null && dt.Rows.Count > 0) { workbook = new HSSFWorkbook(); sheet = workbook.CreateSheet("Sheet0");//創(chuàng)建一個名稱為Sheet0的表 int rowCount = dt.Rows.Count;//行數(shù) int columnCount = dt.Columns.Count;//列數(shù) //設置列頭 row = sheet.CreateRow(0);//excel第一行設為列頭 for (int c = 0; c < columnCount; c++) { cell = row.CreateCell(c); cell.SetCellValue(dt.Columns[c].ColumnName); } //設置每行每列的單元格, for (int i = 0; i < rowCount; i++) { row = sheet.CreateRow(i + 1); for (int j = 0; j < columnCount; j++) { cell = row.CreateCell(j);//excel第二行開始寫入數(shù)據(jù) cell.SetCellValue(dt.Rows[i][j].ToString()); } } using (fs = File.OpenWrite(txtPath)) { workbook.Write(fs);//向打開的這個xls文件中寫入數(shù)據(jù) result = true; } } MessageBox.Show("導出成功"); return result; } catch (Exception) { if (fs != null) { fs.Close(); } return false; } }
3.3 給畫面添加SaveFileDialog
首先在工具箱里找到SaveFileDialog(如果不知到工具箱在哪的可以點擊上方的【視圖】–> 【工具箱】)
點住SaveFileDialog拖入頁面中效果如上圖所示
3.4 引入命名空間
將下方命名空間引入到你按鈕所在的cs中(主要是3、4)
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Data.OleDb;
3.5 給按鈕添加click事件
給按鈕添加click事件(直接雙擊按鈕即可),并在click函數(shù)中插入以下代碼
//打開文件對話框,導出文件 SaveFileDialog saveFileDialog1 = new SaveFileDialog(); saveFileDialog1.Title = "保存文件"; saveFileDialog1.Filter = "Excel 文件(*.xls)|*.xls|Excel 文件(*.xlsx)|*.xlsx|所有文件(*.*)|*.*"; saveFileDialog1.FileName = "用戶信息.xls"; //設置默認另存為的名字 if (this.saveFileDialog1.ShowDialog() == DialogResult.OK) { string txtPath = this.saveFileDialog1.FileName; string sql = "select ID as ID,UserName as 用戶名,LoginAccount as 賬號,UserPower as 用戶權限,Founder as 創(chuàng)建者,Addtime as 創(chuàng)建日期,Activestate as 狀態(tài) from UserData"; SqlHelp sqlHelper = new SqlHelp(); DataTable dt = sqlHelper.GetDataTableValue(sql); NPOIHelper.DataTableToExcel(dt, txtPath); }
注意:上面的saveFileDialog1要和你視圖里的一樣一般沒問題,sql語句我就不詳細講了不會的可以看我其他文章。
4、 成功
相信大家根據(jù)我的步驟應該都能成功了,如果成功了別忘了三連哦!如果在操作過程中遇到什么問題記得評論或者私信。
5、寫在最后
到此這篇關于C# Winform中DataGridView導出為Excel的實現(xiàn)示例的文章就介紹到這了,更多相關C# Winform中DataGridView導出為Excel內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
C#獲得MAC地址(網(wǎng)卡序列號)的實現(xiàn)代碼
這篇文章主要介紹了C#獲得MAC地址的實現(xiàn)代碼,需要的朋友可以參考下2014-02-02C#使用PPT組件的CreateVideo方法實現(xiàn)視頻生成
這篇文章主要為大家詳細介紹了C#如何使用PPT組件的CreateVideo方法實現(xiàn)視頻生成,文中的示例代碼講解詳細,有需要的小伙伴可以跟隨小編一起學習一下2023-10-10