C#导出到Excel

将数据导出到现有的xls表单的最佳方法是哪一种。 我需要支持许多版本的Excel。 如果我使用Visual Basic。 我会使用CreateObject(“Excel.application”)代码,这将做我所需要的。 什么是在C#中的等效? 我会喜欢它在任何版本上工作,如果可能的话,还有没有MS Office的电脑。 请不要花钱的第三方组件。 我们穷:)。

TY

使用C#写入Excel可以使用Interop.Excel完成以下是一个带屏幕截图的不错教程,可帮助实现此目的。

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

内置的function可以将ASP.Net网格导出为ex​​cel。 它给最终用户一点警告信息,但它的工作。

这里描述: C Sharp Corner

如果你想打开一个Excel文档,然后添加内容,最简单的方法之一(无需安装Excel)是获得第三方库(可能有一些开源解决scheme),可以读取和保存excel文件。

我知道你说没有第三方,但原因似乎是成本。

我使用的库是GemBox。 只要电子表格不是太大(150行,最多5张工作表),它就是免费的。 对我来说这是没有问题的,而且工作得很好。

http://www.gemboxsoftware.com/GBSpreadsheet.htm

还有一些开源选项。

如果您正在写入XML格式,那么ExcelPackage是免费的(GPL),并且可以为您工作:

http://excelpackage.codeplex.com/

如果您不想使用XML而只使用其他格式,我会听到有关ExcelLibrary(LGPL)的好消息:

http://code.google.com/p/excellibrary/

还有一个JExcel库(LGPL)的C#端口:

http://www.chrislaforetsoftware.com/products.html

Excel导出

我为此使用EP Plus Excel Export。 从Nuget添加EP Plus库到您的项目中。 然后将此类添加到您的项目。

ExcelExport.cs

尝试

并在MVC上使用它:

 public ActionResult ExportToExcel(string cid) { var customerList = new List<DtoCustomer>(); customerList = CustomerFactory.Gets(); ExcelExport.EpplusExportToExcelFromObjectList(customerList.ToList<object>(), "Customer List", true); return null; } 

您也可以定义Excel文档中显示哪个名称的列。 你必须为此创build一个属性类。

ExportAttribute

 using System.Attribute; public class ExportAttribute : Attribute { public string DisplayName { get; set; } public bool IsVisible { get; set; } } 

类和实施

然后,将这个属性实现给你的类:

 public class DtoCustomer { [ExportAttribute(DisplayName = "#", IsVisible = false)] public int ID { get; set; } [ExportAttribute(DisplayName = "Customer Name", IsVisible = true)] public string Name{ get; set; } [ExportAttribute(DisplayName = "Customer Surname", IsVisible = true)] public string Surname { get; set; } }