[英]C# export to excel
这是将数据导出到现有xls表的最佳方法。 我需要支持许多版本的excel。 如果我使用的是Visual Basic。 我会使用CreateObject(“ Excel.application”)代码来完成我需要的工作。 C#中的等效项是什么? 我希望它可以在任何版本上使用,如果可能的话,也可以在没有ms office的计算机上使用。 请不要花费任何第三方资源。 我们很穷:)。
TY
使用Interop.Excel
可以完成使用C#编写Excel的操作。这是一个不错的教程,提供了屏幕截图,可帮助您实现这一目标。
http://csharp.net-informations.com/excel/csharp-excel-tutorial.htm
我为此使用EP Plus Excel Export。 将Nuget的 EP Plus库添加到您的项目中。 然后将此类添加到您的项目。
并在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文档上显示哪个名称的列。 您必须为此创建一个属性类。
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; }
}
有内置的功能可将ASP.Net网格导出为excel。 它会向最终用户发出一些警告消息,但它可以工作。
描述如下: C Sharp Corner
如果要打开excel文档然后添加内容,最简单的方法之一(不要求安装excel)是获取可以读取和保存的3rd party lib(可能有一些开源解决方案) 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#的端口:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.