发布日期:2018-03-26
用C#创建一个Excel(.xls和.xlsx)文件+ 查看更多
用C#创建一个Excel(.xls和.xlsx)文件
+ 查看更多
发布日期:2018-02-26 17:24
分类:C#
浏览次数:645
如下:我想用C#创建一个Excel表格而不需要在机器上安装Excel,我该怎么编码呢?
回答
你可以使用一个名为 ExcelLibrary 的包,它是发布在google code上免费,开源的包。
ExcelLibrary
上面提及的看起来像一个PHP ExcelWriter的端口,它现在还不能创建.xlsx格式的文件,但他们正在添加这个功能。
它简单、存储小、易用,再加上它有一个DataSetHelper,能让你使用DataSets 和DataTables,以便更加轻松地使用Excel数据.
ExcelLibrary 似乎现在只能使用老版本的Excel格式(.xls),但将会对Excel 2007/2010版的较新的格式提供支持。
你也可以使用EPPlus,它仅仅支持Excel 2007/2010版的格式(.xlsx文件)。
评论中的包有一些已知的Bug,总之,EPPlus似乎是最好的选择,它似乎更加频繁的更新和记录文档。
同时,EPPlus已经支持了Pivot Tables,ExcelLibrary可能也有一定的支持(在ExcelLibrary Pivot Table块)
下面有两个链接以供参考:
https://code.google.com/archive/p/excellibrary
http://epplus.codeplex.com/
上面提及的看起来像一个PHP ExcelWriter的端口,它现在还不能创建.xlsx格式的文件,但他们正在添加这个功能。
它简单、存储小、易用,再加上它有一个DataSetHelper,能让你使用DataSets 和DataTables,以便更加轻松地使用Excel数据.
ExcelLibrary 似乎现在只能使用老版本的Excel格式(.xls),但将会对Excel 2007/2010版的较新的格式提供支持。
你也可以使用EPPlus,它仅仅支持Excel 2007/2010版的格式(.xlsx文件)。
评论中的包有一些已知的Bug,总之,EPPlus似乎是最好的选择,它似乎更加频繁的更新和记录文档。
同时,EPPlus已经支持了Pivot Tables,ExcelLibrary可能也有一定的支持(在ExcelLibrary Pivot Table块)
下面有两个链接以供参考:
https://code.google.com/archive/p/excellibrary
http://epplus.codeplex.com/
下面是 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文件,但是上面的方法是真正影响我的。