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

咨询区

  • mistrmark

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

回答区

  • Mike Webb

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

//Create the data set and table
DataSet ds = new DataSet("New_DataSet");
DataTable dt = new DataTable("New_DataTable");

//Set the locale for each
ds.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
dt.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;

//Open a DB connection (in this example with OleDB)
OleDbConnection con = new OleDbConnection(dbConnectionString);
con.Open();

//Create a query and fill the data table with the data from the DB
string sql = "SELECT Whatever FROM MyDBTable;";
OleDbCommand cmd = new OleDbCommand(sql, con);
OleDbDataAdapter adptr = new OleDbDataAdapter();

adptr.SelectCommand = cmd;
adptr.Fill(dt);
con.Close();

//Add the table to the data set
ds.Tables.Add(dt);

//Here's the easy part. Create the Excel worksheet from the data set
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。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值