C# 不依赖office组件,从datagridview导出excel

今天用到了从datagridview到excel的导出功能。
发现NOPI的控件十分好用。
整理一下,方便自己以后使用。也方便大家使用。
这里使用的是NOPI,从nuget管理器获取
在这里插入图片描述
在这里插入图片描述
封装好的excelhelper,这里只需要传两个参数,文件的全路径和datagridview对象,就可以导出成excel

using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace _03_DGV_TO_EXECL
{
    public static class NPOI_DGVtoExcel_helper
    {
        public static int SaveToExcelNew(string filePath, DataGridView dataGridView)
        {
            //int 记录返回结果1.导出成功  2.文件重名  3.错误信息 0.成功  4.行数超过excel文件限制
            int result;

            FileStream fs = null;//创建一个新的文件流
            HSSFWorkbook workbook = null;//创建一个新的Excel文件
            ISheet sheet = null;//为Excel创建一张工作表

            //定义行数、列数、与当前Excel已有行数
            int rowCount = dataGridView.RowCount;//记录表格中的行数
            int colCount = dataGridView.ColumnCount;//记录表格中的列数

            //为了防止出错,这里应该判定一下文件与文件是否存在
            //  if (File.Exists(filePath))
            //{
              //  return 2;  //这里简单的只写了返回一个值,表示文件已经存在,不要覆盖。
            //感兴趣的,可以自己写一个自动改名代码,避免覆盖的同时,还可以将文件自动另存。
            //}

            //创建工作表
            try
            {
                fs = new FileStream(filePath, FileMode.Create, FileAccess.Write);
                workbook = new HSSFWorkbook();
                sheet = workbook.CreateSheet("Sheet1");
                IRow row = sheet.CreateRow(0);
                for (int j = 0; j < colCount; j++)  //列循环
                {
                    if (dataGridView.Columns[j].Visible && dataGridView.Rows[0].Cells[j].Value != null)
                    {
                        ICell cell = row.CreateCell(j);//创建列
                        cell.SetCellValue(dataGridView.Columns[j].HeaderText.ToString());//更改单元格值                  
                    }
                }
            }
            catch 
            {
                result = 3;
                throw;
                return result;
            }

            for (int i = 0; i < rowCount; i++)      //行循环
            {
                //防止行数超过Excel限制
                if (i >= 65536)
                {
                    result = 4;
                    break;
                }
                IRow row = sheet.CreateRow(1 + i);  //创建行
                for (int j = 0; j < colCount; j++)  //列循环
                {
                    if (dataGridView.Columns[j].Visible && dataGridView.Rows[i].Cells[j].Value != null)
                    {
                        ICell cell = row.CreateCell(j);//创建列
                        cell.SetCellValue(dataGridView.Rows[i].Cells[j].Value.ToString());//填充单元格值                  
                    }
                }
            }
            try
            {
                workbook.Write(fs);
                result = 1;//成功
            }
            catch
            {
                result = 3;
                return result;
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                    fs.Dispose();
                }
                workbook = null;
            }
            return result;
        }

    }
}

创建一个SaveFileDialog控件对象,拿到一个全路径
调用的代码

 private void button2_Click(object sender, EventArgs e)
        {
            //创建和初始化一个SaveFileDialog
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Title = "导出Excel文件";//标题
            sfd.Filter = "Excel(*.xls)|*.xls";//设置文件类型
            sfd.FileName = "新建excel";//设置默认文件名
            sfd.DefaultExt = "xls";//设置默认格式(可以不设)
            sfd.AddExtension = true;//设置自动在文件名中添加扩展名
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                int r= NPOI_DGVtoExcel_helper.SaveToExcelNew(sfd.FileName, dataGridView1);//调用NPOI_DGVtoExcel_helper
                switch (r)
                {
                    //int 记录返回结果1.导出成功  2.文件重名  3.错误信息 0.成功  4.行数超过excel文件限制
                    case 1: MessageBox.Show("导出成功:" + sfd.FileName);
                        break;
                    //case 2:MessageBox.Show("文件已经存在");//启用这行代码就不会覆盖文件
                    //    break;
                    case 4:MessageBox.Show("行数超过excel限制");
                        break;
                    default:
                        break;
                }

            }
           
        }

就这么简单,几乎不用写代码,就实现了导出excel。不用恶心的调试各种office的问题。很实用。推荐。

发布了55 篇原创文章 · 获赞 4 · 访问量 1412

猜你喜欢

转载自blog.csdn.net/BowenXu11/article/details/104807677