網(wǎng)站首頁(yè) 編程語(yǔ)言 正文
C#?Winform中DataGridView導(dǎo)出為Excel的實(shí)現(xiàn)示例_C#教程
作者:嵌入式悅翔園 ? 更新時(shí)間: 2022-07-03 編程語(yǔ)言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)始寫入數(shù)據(jù)
cell.SetCellValue(dt.Rows[i][j].ToString());
}
}
using (fs = File.OpenWrite(txtPath))
{
workbook.Write(fs);//向打開(kāi)的這個(gè)xls文件中寫入數(shù)據(jù)
result = true;
}
}
MessageBox.Show("導(dǎo)出成功");
return result;
}
catch (Exception)
{
if (fs != null)
{
fs.Close();
}
return false;
}
}
3.3 給畫面添加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、寫在最后
原文鏈接:https://blog.csdn.net/qq_45172832/article/details/124635582
相關(guān)推薦
- 2022-11-05 Golang操作命令行的幾種方式總結(jié)_Golang
- 2022-12-26 python畫圖時(shí)linestyle,color和loc參數(shù)的設(shè)置方式_python
- 2022-05-16 深入理解docker鏡像的分層(小白必看)_docker
- 2022-06-07 python?DataFrame中stack()方法、unstack()方法和pivot()方法淺析
- 2021-12-08 linux中g(shù)rub啟動(dòng)引導(dǎo)程序的加密介紹_Linux
- 2021-12-10 C#實(shí)現(xiàn)簡(jiǎn)易灰度圖和酷炫HeatMap熱力圖winform(附DEMO)_C#教程
- 2023-05-05 Linux中g(shù)rep命令詳解_linux shell
- 2023-01-11 一文帶你解密Python迭代器的實(shí)現(xiàn)原理_python
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲(chǔ)小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過(guò)濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯(cuò)誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡(jiǎn)單動(dòng)態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對(duì)象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支