You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将DataGridView中的数据导出至Excel?

替代Microsoft.Office.Interop.Excel的简便Excel导出方案

我之前用Microsoft.Office.Interop.Excel做数据导出时栽了跟头,遇到了组件加载错误:

Could not load file or assembly 'office, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bc111e9429c' or one of its dependencies. The system cannot find the file specified

折腾半天后放弃了Interop,找到了更省事的方案——用轻量开源库实现,完全不需要依赖目标机器安装Office:

  • 推荐用EPPlus或者NPOI这类库,直接通过代码生成Excel文件
  • 不用处理Office版本兼容、COM组件权限这类麻烦问题
  • 代码实现简单,性能也更稳定

拿EPPlus举个例子,核心代码就几行:

using OfficeOpenXml;
using System.IO;

// 初始化Excel包
using (var excelPackage = new ExcelPackage())
{
    // 添加工作表
    var worksheet = excelPackage.Workbook.Worksheets.Add("数据列表");
    
    // 写入表头
    worksheet.Cells["A1"].Value = "ID";
    worksheet.Cells["B1"].Value = "名称";
    
    // 写入数据行
    worksheet.Cells["A2"].Value = 1;
    worksheet.Cells["B2"].Value = "示例数据";
    
    // 保存到文件
    excelPackage.SaveAs(new FileInfo(@"D:\导出结果.xlsx"));
}

这种方案彻底避开了Interop的各种坑,部署起来也省心,适合遇到同样问题的开发者参考。

内容的提问来源于stack exchange,提问作者havanri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 07:20:28