• C#winform导出DataGridView数据到Excel表


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

    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);
         }
     }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    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);
           }
       }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28

    报错信息
    {"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,即可解决该问题。
    在这里插入图片描述

    在这里插入图片描述
    原文链接

  • 相关阅读:
    哈夫曼树相关操作(C-数据结构)
    SpringCloud (四) ——Nacos配置管理
    初次使用IntelliJ IDEA从零开始学习创建maven项目
    TCP面试
    FPGA project : IIC_wr_eeprom
    CentOS上升级glibc2.17至glibc2.31
    算法笔记-归并排序
    Jenkins自动化测试
    Linux学习笔记——Shell和Bash
    5分钟就能实现的API监控,有什么理由不做呢?
  • 原文地址:https://blog.csdn.net/NJJML/article/details/132729535