C#winform导出DataGridView数据到Excel表

前提:NuGet安装EPPlus,选择合适的能兼容当前.net framwork的版本

主要代码:

csharp 复制代码
private void btn_export_Click(object sender, EventArgs e)
{
     SaveFileDialog saveFileDialog = new SaveFileDialog();
     saveFileDialog.Filter = "Excel Files|*.xlsx|All Files|*.*"; // 设置文件筛选器
     saveFileDialog.Title = "选择保存位置"; // 设置对话框标题
     saveFileDialog.FileName = "data.csv"; // 设置默认文件名

     if (saveFileDialog.ShowDialog() == DialogResult.OK)
     {
         string filePath = saveFileDialog.FileName;
         // 在这里执行保存文件的操作,可以调用之前的导出到Excel的方法
         ExportToExcel(Dgv, filePath);
     }
 }
csharp 复制代码
private void ExportToExcel(DataGridView dataGridView, string filePath)
{
       // 创建一个新的 Excel 包
       using (ExcelPackage excelPackage = new ExcelPackage())
       {
           // 添加一个工作表
           ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets.Add("Sheet1");

           // 将 DataGridView 的列标题复制到工作表的第一行
           for (int i = 0; i < dataGridView.Columns.Count; i++)
           {
               worksheet.Cells[1, i + 1].Value = dataGridView.Columns[i].HeaderText;
           }

           // 将 DataGridView 的数据复制到工作表中
           for (int i = 0; i < dataGridView.Rows.Count; i++)
           {
               for (int j = 0; j < dataGridView.Columns.Count; j++)
               {
                   worksheet.Cells[i + 2, j + 1].Value = dataGridView.Rows[i].Cells[j].Value;
               }
           }

           // 保存 Excel 文件
           FileInfo excelFile = new FileInfo(filePath);
           excelPackage.SaveAs(excelFile);
       }
   }

报错信息
{"Please set the ExcelPackage.LicenseContext property. See https://epplussoftware.com/developers/licenseexception"}

使用的是 EPPlus 5.0.4 或更高版本,因此需要设置 ExcelPackage.LicenseContext 属性来避免许可证错误。(在 应用程序引用了正确的NuGet包,即 EPPlus 的前提下)即:在设置属性之前,先引入 System.ComponentModel 命名空间,然后在窗体的构造函数中设置 ExcelPackage.LicenseContext 属性为 LicenseContext.NonCommercial,即可解决该问题。


原文链接

相关推荐
Dxy12393102164 分钟前
Python PDFplumber详解:从入门到精通的PDF处理指南
开发语言·python·pdf
EutoCool1 小时前
Qt:布局管理器Layout
开发语言·c++·windows·嵌入式硬件·qt·前端框架
Cyanto2 小时前
Spring注解IoC与JUnit整合实战
java·开发语言·spring·mybatis
写不出来就跑路2 小时前
WebClient与HTTPInterface远程调用对比
java·开发语言·后端·spring·springboot
悠哉清闲2 小时前
C++ MediaCodec H264解码
开发语言·c++
张人玉2 小时前
c#中Random类、DateTime类、String类
开发语言·c#
Jinkxs2 小时前
JavaScript性能优化实战技术
开发语言·javascript·性能优化
future14123 小时前
游戏开发日记
数据结构·学习·c#
ydm_ymz4 小时前
C语言初阶4-数组
c语言·开发语言
presenttttt4 小时前
用Python和OpenCV从零搭建一个完整的双目视觉系统(六 最终篇)
开发语言·python·opencv·计算机视觉