• 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,即可解决该问题。
    在这里插入图片描述

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

  • 相关阅读:
    SpringSecurity6 | 自动配置(下)
    第59节——redux-toolkit中的createSelector
    动态缩略图清晰度优化
    JumpServer rce深入剖析
    Scrapy 2.6.2 代理设置,Proxy-Authorization 安全漏洞修复
    设计循环队列---力扣622
    BFSの笔记
    《安富莱嵌入式周报》第279期:强劲的代码片段搜索工具,卡内基梅隆大学安全可靠C编码标准,Nordic发布双频WiFi6 nRF7002芯片
    Winform开源布局组件DockPanelSuite使用
    从0开始学习JavaScript--JavaScript使用Promise
  • 原文地址:https://blog.csdn.net/NJJML/article/details/132729535