从C#创buildExcel(.XLS和.XLSX)文件

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

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

ExcelLibrary

这看起来是上面提到的PHP ExcelWriter的一个端口。 它不会写入新的.xlsx格式,但是他们正在努力增加这个function。

这是非常简单,小巧,易于使用。 另外它有一个DataSetHelper,可以让你使用DataSets和DataTables轻松处理Excel数据。

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

您也可以使用仅适用于Excel 2007/2010格式文件(.xlsx文件)的EPPlus 。

如评论中所述,每个图书馆都有一些已知的错误。 总之,随着时间的推移,EPPlus似乎是最好的select。 它似乎更积极地更新和logging。

此外,正如下面的@АртёмЦарионов所指出的,EPPlus支持数据透视表,ExcelLibrary可能有一些支持( ExcelLibrary中的数据透视表问题 )

以下是一些快速参考的链接:
ExcelLibrary – GNU较小的GPL
EPPlus – GNU 较低 通用公共许可证(LGPL)

这里是ExcelLibrary的一些示例代码:

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

创buildExcel文件非常简单。 您也可以手动创buildExcel文件,但上述function是真正给我留下深刻印象的。

如果您对xlsx格式感到满意,请尝试使用我的codeplex GitHub项目。 EPPlus 。 从ExcelPackage的源头开始它,但今天它是一个完全重写。 支持范围,单元格样式,图表,形状,图片,名称范围,自动filter和许多其他的东西。

我已经成功地使用了以下开源项目:

  • 用于OOXML格式的ExcelPackage(Office 2007)

  • NPOI .XLS格式(Office 2003)。 NPOI 2.0 (Alpha)也支持XLSX。

看看我的博客文章:

在C#中创buildExcel电子表格.XLS和.XLSX

NPOI与Excel表和dynamic图表

那么使用Open XML SDK 2.0 for Microsoft Office如何?

一些好处:

  • 不需要安装Office
  • 由Microsoft = MSDN文档制作而成
  • 只有一个.net dll在项目中使用
  • SDK附带了许多工具,比如diff,validator等

链接:

  • 下载SDK
  • 主MSDN登陆
  • “我如何…”入门页面
  • blogs.MSDN brian_jones 宣布SDK
  • blogs.MSDN brian_jones 描述SDK处理大文件而不崩溃(不像DOM方法)

您可以使用OLEDB创build和操作Excel文件。 选中此项: 使用OLEDB读取和写入Excel 。

典型例子:

 using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\temp\\test.xls;Extended Properties='Excel 8.0;HDR=Yes'")) { conn.Open(); OleDbCommand cmd = new OleDbCommand("CREATE TABLE [Sheet1] ([Column1] string, [Column2] string)", conn); cmd.ExecuteNonQuery(); } 

编辑 – 更多链接:

  • 嘿,脚本专家! 如何在不使用Excel的情况下从Excel中读取数据?
  • 如何使用ADO.NET使用Visual Basic .NET检索和修改Excel工作簿中的logging
  • 使用ADO.NET C#DbProviderFactory读取和写入Excel电子表格

商业解决scheme, SpreadsheetGear for .NET将做到这一点。

您可以在这里看到实时的ASP.NET(C#和VB)示例,并在此处下载评估版本。

免责声明:我自己的SpreadsheetGear LLC

我用过的几个选项:

如果XLSX是必须的: ExcelPackage是一个好的开始,但是当开发人员退出时,它就离开了。 ExML从那里拿起并添加了一些function。 ExML不是一个坏的select,我仍然在几个制作网站中使用它。

但是,对于我所有的新项目,我正在使用Apache POI的.NET端口NPOI 。 NPOI 2.0(Alpha)也支持XLSX。

一个非常轻量级的选项可能是使用HTML表格。 只需在文件中创build头部,主体和表格标签,并将其另存为扩展名为.xls的文件。 有可用于设置输出样式的Microsoft特定属性,包括公式。

我意识到,您可能不会在Web应用程序中编写此代码,但这里是通过HTML表格组成Excel文件的示例 。 如果您正在编写控制台应用程序,桌面应用程序或服务,则可以使用此技术。

你可以使用ExcelXmlWriter http://www.carlosag.net/Tools/ExcelXmlWriter/

它工作正常。

你实际上可能想检查互操作类 。 你说没有OLE(这不是),但互操作类很容易使用。

如果你还没有尝试过,你可能会留下深刻的印象。

请注意微软在这方面的立场 :

Microsoft目前不推荐并不支持从任何无人参与的非交互式客户端应用程序或组件(包括ASP,ASP.NET,DCOM和NT服务)自动化Microsoft Office应用程序,因为Office可能会出现不稳定的行为和/或在此环境中运行Office时发生死锁。

如果您正在创buildExcel 2007/2010文件,请尝试以下开源项目: http : //closedxml.codeplex.com

它提供了一种面向对象的方式来处理文件(类似于VBA)而不用处理XML文档的麻烦。 它可以被任何.NET语言(如C#和Visual Basic(VB))使用。

ClosedXML允许您在没有Excel应用程序的情况下创buildExcel 2007/2010文件。 典型的例子是在Web服务器上创buildExcel报告:

 var workbook = new XLWorkbook(); var worksheet = workbook.Worksheets.Add("Sample Sheet"); worksheet.Cell("A1").Value = "Hello World!"; workbook.SaveAs("HelloWorld.xlsx"); 

这里有一个完全免费的C#库,可以使用OpenXML库从DataSetDataTableList<>导出为一个真正的Excel 2007 .xlsx文件:

http://mikesknowledgebase.com/pages/CSharp/ExportToExcel.htm

免费提供完整的源代码,并附有说明和演示应用程序。

将这个类添加到您的应用程序后,您可以在一行代码中将DataSet导出到Excel:

 CreateExcelFile.CreateExcelDocument(myDataSet, "C:\\Sample.xlsx"); 

这并没有比这更简单

而且它甚至不需要在您的服务器上存在Excel。

您可以考虑使用XML Spreadsheet 2003格式创build您的文件。 这是一个简单的XML格式,使用一个很好的文档模式 。

你可能想看看http://www.gemboxsoftware.com/GBSpreadsheetFree.htm

他们有一个免费版本的所有function,但限于每行150行,每张工作簿5张,如果这符合您的需求。

我还没有必要自己使用它,但看起来很有趣。

对于较小的Excel文件,各种Office 2003 XML库可用。 但是,我发现保存在XML格式中的大型工作簿的大小是一个问题。 例如,我使用的工作簿在新的(而且被认为是更紧密的)XMBX格式成为40MB的XML文件。

据我的研究,有两个商业软件包允许输出到旧的二进制文件格式。 他们是:

  • Gembox
  • ComponentOne Excel

两者都不便宜(我认为分别是500美元和800美元)。 但两者都独立于Excel本身。

我会好奇的是OpenOffice.org的Excel输出模块。 我想知道他们是否可以从Java移植到.Net。

我同意生成XML Spreadsheets,下面是一个关于如何为C#3(每个人只是在VB 9:P的博客) http://www.aaron-powell.com/linq-to-xml-to-高强;

只是想添加另一个参考直接解决您的问题的第三方解决scheme: http : //www.officewriter.com

(免责声明:我为SoftArtisans,OfficeWriter公司工作)

好,

您也可以使用Aspose等第三方库。

这个库有一个好处,它不需要在您的机器上安装Excel,这将是理想的情况下。

Syncfusion Essential XlsIO可以做到这一点。 它不依赖于Microsoft Office,并且对不同的平台有特定的支持。

  • ASP.NET
  • ASP.NET MVC
  • UWP
  • Xamarin
  • WPF和Windows窗体
  • Windows服务和基于批处理的操作

代码示例:

 //Creates a new instance for ExcelEngine. ExcelEngine excelEngine = new ExcelEngine(); //Loads or open an existing workbook through Open method of IWorkbooks IWorkbook workbook = excelEngine.Excel.Workbooks.Open(fileName); //To-Do some manipulation| //To-Do some manipulation //Set the version of the workbook. workbook.Version = ExcelVersion.Excel2013; //Save the workbook in file system as xlsx format workbook.SaveAs(outputFileName); 

如果您符合条件(低于100万美元的收入),整套控制系统将通过社区许可计划免费提供。 注意:我为Syncfusion工作。

我刚刚使用FlexCel.NET ,发现它是一个优秀的图书馆! 我并不是说太多的软件产品。 在这里给出整个销售点没有意义,你可以阅读他们网站上的所有function。

这是一个商业产品,但是如果你购买它,你可以得到完整的资源。 所以我想你可以编译成你的程序集,如果你真的想。 否则,它只是一个额外的组装xcopy – 没有configuration或安装或类似的东西。

如果没有.NET框架的第三方库,我不认为你会find办法做到这一点,显然,它没有内置的支持,OLE自动化只是一个痛苦的世界。

下面是使用LINQ to XML进行处理的一种方法,并附有示例代码:

使用LINQ to XML快速导入和导出Excel数据

这有点复杂,因为你必须导入命名空间等等,但它确实可以避免任何外部依赖。

(另外,当然,它是VB.NET,而不是C#,但是您可以始终在自己的项目中使用XML文本来分离VB .NET的东西,并在C#中执行其他所有操作。

某些第三方组件供应商(如Infragistics或Syncfusion)提供了非常好的Excel导出function,不需要安装Microsoft Excel。

由于这些供应商还提供高级UI网格组件,因此如果您希望Excel导出的样式和布局模拟应用程序的用户界面中的网格的当前状态,则这些组件特别方便。

如果您的导出是为了执行服务器端,侧重于要导出的数据,并且没有链接到UI,那么我会select一个免费的开源选项(例如ExcelLibrary)。

我以前参与过试图在Microsoft Office套件上使用服务器端自动化的项目。 基于这个经验,我强烈build议不要这样做。

OpenXML也是避免在服务器上安装MS Excel的一个很好的select。由Microsoft提供的Open XML SDK 2.0简化了在一个包中操作Open XML包和底层Open XML模式元素的任务。 Open XML应用程序编程接口(API)封装了开发人员在Open XML包上执行的许多常见任务。

检查一下OpenXML:替代方法,有助于避免在服务器上安装MS Excel

IKVM + POI

或者,您可以使用Interop …

 public class GridViewExportUtil { public static void Export(string fileName, GridView gv) { HttpContext.Current.Response.Clear(); HttpContext.Current.Response.AddHeader( "content-disposition", string.Format("attachment; filename={0}", fileName)); HttpContext.Current.Response.ContentType = "application/ms-excel"; using (StringWriter sw = new StringWriter()) { using (HtmlTextWriter htw = new HtmlTextWriter(sw)) { // Create a form to contain the grid Table table = new Table(); // add the header row to the table if (gv.HeaderRow != null) { GridViewExportUtil.PrepareControlForExport(gv.HeaderRow); table.Rows.Add(gv.HeaderRow); } // add each of the data rows to the table foreach (GridViewRow row in gv.Rows) { GridViewExportUtil.PrepareControlForExport(row); table.Rows.Add(row); } // add the footer row to the table if (gv.FooterRow != null) { GridViewExportUtil.PrepareControlForExport(gv.FooterRow); table.Rows.Add(gv.FooterRow); } // render the table into the htmlwriter table.RenderControl(htw); // render the htmlwriter into the response HttpContext.Current.Response.Write(sw.ToString()); HttpContext.Current.Response.End(); } } } /// <summary> /// Replace any of the contained controls with literals /// </summary> /// <param name="control"></param> private static void PrepareControlForExport(Control control) { for (int i = 0; i < control.Controls.Count; i++) { Control current = control.Controls[i]; if (current is LinkButton) { control.Controls.Remove(current); control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text)); } else if (current is ImageButton) { control.Controls.Remove(current); control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText)); } else if (current is HyperLink) { control.Controls.Remove(current); control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text)); } else if (current is DropDownList) { control.Controls.Remove(current); control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text)); } else if (current is CheckBox) { control.Controls.Remove(current); control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False")); } if (current.HasControls()) { GridViewExportUtil.PrepareControlForExport(current); } } } } 

您好这个解决scheme是导出您的网格视图到您的Excel文件可能会帮助你

您可以使用此库创build格式良好的Excel文件: http : //officehelper.codeplex.com/documentation
见下面的例子:

 using (ExcelHelper helper = new ExcelHelper(TEMPLATE_FILE_NAME, GENERATED_FILE_NAME)) { helper.Direction = ExcelHelper.DirectionType.TOP_TO_DOWN; helper.CurrentSheetName = "Sheet1"; helper.CurrentPosition = new CellRef("C3"); //the template xlsx should contains the named range "header"; use the command "insert"/"name". helper.InsertRange("header"); //the template xlsx should contains the named range "sample1"; //inside this range you should have cells with these values: //<name> , <value> and <comment>, which will be replaced by the values from the getSample() CellRangeTemplate sample1 = helper.CreateCellRangeTemplate("sample1", new List<string> {"name", "value", "comment"}); helper.InsertRange(sample1, getSample()); //you could use here other named ranges to insert new cells and call InsertRange as many times you want, //it will be copied one after another; //even you can change direction or the current cell/sheet before you insert //typically you put all your "template ranges" (the names) on the same sheet and then you just delete it helper.DeleteSheet("Sheet3"); } 

样本看起来像这样:

 private IEnumerable<List<object>> getSample() { var random = new Random(); for (int loop = 0; loop < 3000; loop++) { yield return new List<object> {"test", DateTime.Now.AddDays(random.NextDouble()*100 - 50), loop}; } } 

在C#中一些有用的Excel自动化,你可以从下面的链接find。

http://csharp.net-informations.com/excel/csharp-excel-tutorial.htm

博尔顿。

查看示例如何创buildExcel文件。

C#VB.NET中有例子

它pipe理XSL XSLX和CSV Excel文件。

http://www.devtriogroup.com/ExcelJetcell/Samples

你有没有尝试sylk?

我们曾经用经典的asp作为sylk来生成excelsheets,现在我们也在寻找一个excelgenerater。

sylk的优点是,你可以格式化单元格。

寻找ExtremeML。 这是一个非常酷的库,它使您能够使用OpenXML格式来生成OpenXML文件。

这也是一个OpenSource项目。

http://www.extrememl.com/