• 如何在不安装 Microsoft Office 的情况下生成 Excel 文件?


    咨询区

    • mistrmark

    我的一个项目中有导出 excel 的功能,但我发现运行代码的机器上一定要安装 Excel,否则就找不到 Microsoft.Office.Interop.Excel ,导致运行报错,请问如何解决?

    回答区

    • Mike Webb

    你可以在 nuget 上找一下 ExcelLibrary 包,它是免费开源的,参考如下代码:

    1. //Create the data set and table
    2. DataSet ds = new DataSet("New_DataSet");
    3. DataTable dt = new DataTable("New_DataTable");
    4. //Set the locale for each
    5. ds.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
    6. dt.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
    7. //Open a DB connection (in this example with OleDB)
    8. OleDbConnection con = new OleDbConnection(dbConnectionString);
    9. con.Open();
    10. //Create a query and fill the data table with the data from the DB
    11. string sql = "SELECT Whatever FROM MyDBTable;";
    12. OleDbCommand cmd = new OleDbCommand(sql, con);
    13. OleDbDataAdapter adptr = new OleDbDataAdapter();
    14. adptr.SelectCommand = cmd;
    15. adptr.Fill(dt);
    16. con.Close();
    17. //Add the table to the data set
    18. ds.Tables.Add(dt);
    19. //Here's the easy part. Create the Excel worksheet from the data set
    20. ExcelLibrary.DataSetHelper.CreateWorkbook("MyExcelFile.xls", ds);

    除了 ExcelLibrary 之外,还有一些其他工具包:

    1. EPPlus

    2. NPOI

    • Sogger

    大家觉得用 Open XML SDK 2.0 怎么样?

    它的好处:

    1. 不需要安装 Office。

    2. 由 Microsoft 打造,有正统的 MSDN 文档。

    3. 只需要引用一个 dll 即可。

    4. SDK附带了很多工具,比如:diff,validator 等等。

    • Jan Källman

    如果你倾向于生成 xlsx 格式的excel,可以试试github上的 EPPlus,它是从 ExcelPackage 上发展而来的,发展到今天已经完全重写了,它支持 范围,单元格样式,图标,图形,图片,自动过滤 等等其他一些实用功能。

    点评区

    说实话,前段时间在调试一个老项目时还真遇到了这种情况,真是太坑了,看样子得参考几位大佬提到的sdk重写,个人推荐 EPPlus。

  • 相关阅读:
    基于 MHA 的 MySQL 高可用主从架构
    Java23种设计模式-创建型模式之原型模式
    git pull
    Tauri-Vue3桌面端聊天室|tauri+vite3仿微信|tauri聊天程序EXE
    腾讯云服务器OpenCloudOS操作系统详细介绍
    视频解锁【物联网技术在物联网产业格局的分布与应用】
    Docker
    AI绘画的魅力与未来:人工智能如何重塑艺术创作
    Spring Boot多数据源配置并通过注解实现动态切换数据源
    【蓝桥杯单片机入门记录】动态数码管
  • 原文地址:https://blog.csdn.net/biyusr/article/details/125515027