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 之外,还有一些其他工具包:
EPPlus
NPOI
Sogger:
大家觉得用 Open XML SDK 2.0 怎么样?
它的好处:
不需要安装 Office。
由 Microsoft 打造,有正统的 MSDN 文档。
只需要引用一个 dll 即可。
SDK附带了很多工具,比如:diff,validator 等等。
Jan Källman:
如果你倾向于生成 xlsx 格式的excel,可以试试github上的 EPPlus,它是从 ExcelPackage 上发展而来的,发展到今天已经完全重写了,它支持 范围,单元格样式,图标,图形,图片,自动过滤 等等其他一些实用功能。
说实话,前段时间在调试一个老项目时还真遇到了这种情况,真是太坑了,看样子得参考几位大佬提到的sdk重写,个人推荐 EPPlus。