C# Winform中DataGridView导出为Excel

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

C# Winform中DataGridView导出为Excel

嵌入式悦翔园   2022-06-03 我要评论

1、前言

话不多说,跟着我的步骤保证你也能成功,下面直接开始!

2、效果展示

导出前

在这里插入图片描述

导出后

在这里插入图片描述

3、详细步骤

下面是详细操作步骤,请跟着我的步伐,一步一步进行操作,保证你能够导出成功!

3.1 添加NPOI和NPOI.Excel包

首先请请确定你的vs已经打开了【解决方案资源管理器】,打开步骤见下图:

在这里插入图片描述

在资源管理器中找到【引用】,然后在【引用】上右键选择【管理程序包】并点击,如下图:

在这里插入图片描述

在新打开的窗口中点击【浏览】并在搜索框中依次输入NPOI和NPOI.Excel并进行安装,安装按钮位置如下图:

在这里插入图片描述

待安装完成再进行下一步

3.2 创建NPOIHelper类

首先在资源管理器中选中你的项目,【右键】找到【添加】–>【类】,具体如下图:

在这里插入图片描述

创建一个名字为【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,当然也可以循环读取每个sheet
                            dataTable = new DataTable();
                            if (sheet != null)
                            {
                                int rowCount = sheet.LastRowNum;//总行数
                                if (rowCount > 0)
                                {
                                    IRow firstRow = sheet.GetRow(0);//第一行
                                    int cellCount = firstRow.LastCellNum;//列数

                                    //构建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");//创建一个名称为Sheet0的表
                    int rowCount = dt.Rows.Count;//行数
                    int columnCount = dt.Columns.Count;//列数

                    //设置列头
                    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第二行开始写入数据
                            cell.SetCellValue(dt.Rows[i][j].ToString());
                        }
                    }
                    using (fs = File.OpenWrite(txtPath))
                    {
                        workbook.Write(fs);//向打开的这个xls文件中写入数据
                        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函数中插入以下代码

//打开文件对话框,导出文件
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 创建者,Addtime as 创建日期,Activestate as 状态 from UserData";
    SqlHelp sqlHelper = new SqlHelp();
    DataTable dt = sqlHelper.GetDataTableValue(sql);
    NPOIHelper.DataTableToExcel(dt, txtPath);
}

注意:上面的saveFileDialog1要和你视图里的一样一般没问题,sql语句我就不详细讲了不会的可以看我其他文章。

4、 成功

相信大家根据我的步骤应该都能成功了,如果成功了别忘了三连哦!如果在操作过程中遇到什么问题记得评论或者私信。

5、写在最后

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们