C# Winform中DataGridView導(dǎo)出為Excel的實(shí)現(xiàn)示例
1、前言
話不多說(shuō),跟著我的步驟保證你也能成功,下面直接開(kāi)始!
2、效果展示
導(dǎo)出前

導(dǎo)出后

3、詳細(xì)步驟
下面是詳細(xì)操作步驟,請(qǐng)跟著我的步伐,一步一步進(jìn)行操作,保證你能夠?qū)С龀晒Γ?/p>
3.1 添加NPOI和NPOI.Excel包
首先請(qǐng)請(qǐng)確定你的vs已經(jīng)打開(kāi)了【解決方案資源管理器】,打開(kāi)步驟見(jiàn)下圖:

在資源管理器中找到【引用】,然后在【引用】上右鍵選擇【管理程序包】并點(diǎn)擊,如下圖:

在新打開(kāi)的窗口中點(diǎn)擊【瀏覽】并在搜索框中依次輸入NPOI和NPOI.Excel并進(jìn)行安裝,安裝按鈕位置如下圖:

待安裝完成再進(jìn)行下一步
3.2 創(chuàng)建NPOIHelper類
首先在資源管理器中選中你的項(xiàng)目,【右鍵】找到【添加】–>【類】,具體如下圖:

創(chuàng)建一個(gè)名字為【NPOIHelper.cs】的類并打開(kāi)
3.2.1 導(dǎo)入命名空間
復(fù)制下面的代碼,覆蓋你自動(dòng)生成的命名空間
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 插入代碼
將下面的代碼導(dǎo)入到下圖位置:

public class ExcelUtility
{
/// <summary>
/// 將excel導(dǎo)入到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);//讀取第一個(gè)sheet,當(dāng)然也可以循環(huán)讀取每個(gè)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ù)
//構(gòu)建datatable的列
if (isColumnName)
{
startRow = 1;//如果第一行是列名,則從第二行開(kāi)始讀取
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;
//對(duì)時(shí)間格式(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)建一個(gè)名稱為Sheet0的表
int rowCount = dt.Rows.Count;//行數(shù)
int columnCount = dt.Columns.Count;//列數(shù)
//設(shè)置列頭
row = sheet.CreateRow(0);//excel第一行設(shè)為列頭
for (int c = 0; c < columnCount; c++)
{
cell = row.CreateCell(c);
cell.SetCellValue(dt.Columns[c].ColumnName);
}
//設(shè)置每行每列的單元格,
for (int i = 0; i < rowCount; i++)
{
row = sheet.CreateRow(i + 1);
for (int j = 0; j < columnCount; j++)
{
cell = row.CreateCell(j);//excel第二行開(kāi)始寫(xiě)入數(shù)據(jù)
cell.SetCellValue(dt.Rows[i][j].ToString());
}
}
using (fs = File.OpenWrite(txtPath))
{
workbook.Write(fs);//向打開(kāi)的這個(gè)xls文件中寫(xiě)入數(shù)據(jù)
result = true;
}
}
MessageBox.Show("導(dǎo)出成功");
return result;
}
catch (Exception)
{
if (fs != null)
{
fs.Close();
}
return false;
}
}
3.3 給畫(huà)面添加SaveFileDialog
首先在工具箱里找到SaveFileDialog(如果不知到工具箱在哪的可以點(diǎn)擊上方的【視圖】–> 【工具箱】)

點(diǎn)住SaveFileDialog拖入頁(yè)面中效果如上圖所示
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ù)中插入以下代碼
//打開(kāi)文件對(duì)話框,導(dǎo)出文件
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Title = "保存文件";
saveFileDialog1.Filter = "Excel 文件(*.xls)|*.xls|Excel 文件(*.xlsx)|*.xlsx|所有文件(*.*)|*.*";
saveFileDialog1.FileName = "用戶信息.xls"; //設(shè)置默認(rèn)另存為的名字
if (this.saveFileDialog1.ShowDialog() == DialogResult.OK)
{
string txtPath = this.saveFileDialog1.FileName;
string sql = "select ID as ID,UserName as 用戶名,LoginAccount as 賬號(hào),UserPower as 用戶權(quán)限,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要和你視圖里的一樣一般沒(méi)問(wèn)題,sql語(yǔ)句我就不詳細(xì)講了不會(huì)的可以看我其他文章。
4、 成功
相信大家根據(jù)我的步驟應(yīng)該都能成功了,如果成功了別忘了三連哦!如果在操作過(guò)程中遇到什么問(wèn)題記得評(píng)論或者私信。
5、寫(xiě)在最后
到此這篇關(guān)于C# Winform中DataGridView導(dǎo)出為Excel的實(shí)現(xiàn)示例的文章就介紹到這了,更多相關(guān)C# Winform中DataGridView導(dǎo)出為Excel內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C#計(jì)算程序執(zhí)行過(guò)程花費(fèi)時(shí)間的方法
這篇文章主要介紹了C#計(jì)算程序執(zhí)行過(guò)程花費(fèi)時(shí)間的方法,涉及C#簡(jiǎn)單的時(shí)間運(yùn)算技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-09-09
C#獲得MAC地址(網(wǎng)卡序列號(hào))的實(shí)現(xiàn)代碼
這篇文章主要介紹了C#獲得MAC地址的實(shí)現(xiàn)代碼,需要的朋友可以參考下2014-02-02
C#獲取計(jì)算機(jī)硬件與操作系統(tǒng)的相關(guān)信息
這篇文章介紹了C#獲取計(jì)算機(jī)硬件與操作系統(tǒng)相關(guān)信息的方法,文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-04-04
C#表達(dá)式中的動(dòng)態(tài)查詢?cè)斀狻咀g】
這篇文章主要給大家介紹了關(guān)于C#表達(dá)式中動(dòng)態(tài)查詢的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01
C#使用PPT組件的CreateVideo方法實(shí)現(xiàn)視頻生成
這篇文章主要為大家詳細(xì)介紹了C#如何使用PPT組件的CreateVideo方法實(shí)現(xiàn)視頻生成,文中的示例代碼講解詳細(xì),有需要的小伙伴可以跟隨小編一起學(xué)習(xí)一下2023-10-10
VS里使用C#制作窗口應(yīng)用的項(xiàng)目實(shí)踐
C#窗體的頻率使用特別高,本文主要介紹了VS里使用C#制作窗口應(yīng)用的項(xiàng)目實(shí)踐,具有一定的參考價(jià)值,感興趣的可以了解一下2024-02-02
C#導(dǎo)入導(dǎo)出Excel數(shù)據(jù)的兩種方法
這篇文章主要為大家詳細(xì)介紹了C#導(dǎo)入導(dǎo)出Excel數(shù)據(jù)的兩種方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-03-03

