[英]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.