如何在不安装 Microsoft Office 的情况下用 C# 创建 Excel(.XLS 和 .XLSX)文件?

2024-01-11

如何使用 C# 创建 Excel 电子表格,而不需要在运行代码的计算机上安装 Excel?


您可以使用名为 ExcelLibrary 的库。这是一个发布在 Google Code 上的免费开源库:

Excel图书馆 https://code.google.com/archive/p/excellibrary/

这看起来是您上面提到的 PHP ExcelWriter 的端口。它还不会写入新的 .xlsx 格式,但他们正在努力添加该功能。

它非常简单、小巧且易于使用。另外,它还有一个 DataSetHelper,可让您使用 DataSet 和 DataTable 轻松处理 Excel 数据。

ExcelLibrary 似乎仍然只适用于较旧的 Excel 格式(.xls 文件),但将来可能会添加对较新的 2007/2010 格式的支持。

您还可以使用EPPlus https://github.com/JanKallman/EPPlus,仅适用于 Excel 2007/2010 格式文件(.xlsx 文件)。还有NPOI https://github.com/tonyqus/npoi两者都适用。

正如评论中所述,每个库都有一些已知的错误。总而言之,随着时间的推移,EPPlus 似乎是最佳选择。它似乎也更加积极地更新和记录。

另外,正如下面@АртёмЦарионов 所指出的,EPPlus 支持数据透视表,ExcelLibrary 可能有一些支持(ExcelLibrary 中的数据透视表问题 https://code.google.com/archive/p/excellibrary/issues/98)

以下是一些供快速参考的链接:
Excel图书馆 https://code.google.com/archive/p/excellibrary/ - GNU 较小的 GPL https://www.gnu.org/licenses/lgpl.html
EPPlus https://github.com/JanKallman/EPPlus - GNU (LGPL) - 不再维护 https://github.com/JanKallman/EPPlus#license
EPPlus 5 https://www.epplussoftware.com/ - Polyform 非商业版 - 从 2020 年 5 月开始 https://www.epplussoftware.com/en/LicenseOverview
NPOI https://github.com/tonyqus/npoi - 阿帕奇许可证 https://github.com/tonyqus/npoi/blob/master/LICENSE

下面是 ExcelLibrary 的一些示例代码:

以下是从数据库获取数据并从中创建工作簿的示例。请注意,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);

创建 Excel 文件就是这么简单。你也可以手动创建Excel文件,但上面的功能才是真正让我印象深刻的。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在不安装 Microsoft Office 的情况下用 C# 创建 Excel(.XLS 和 .XLSX)文件? 的相关文章

随机推荐