Which is the best way to export data to an existing xls sheet. I needs to support many versions of excel. If i was using Visual basic. I would use the CreateObject(\"Excel.a
If you are wanting to Open an excel doc and then add content, one of the easiest way (w/o requiring excel to be installed) is to get a 3rd party lib ( there are probably some open source solutions) that can read and save excel files.
Writing to Excel using C# can be accomplished using the Interop.Excel
Here is a nice tutorial with screen shots to help make this happen.
http://csharp.net-informations.com/excel/csharp-excel-tutorial.htm
I use EP Plus Excel Export for this. Add EP Plus library from Nuget to your project. Then add this class to your project.
ExcelExport.cs
And use it on MVC:
public ActionResult ExportToExcel(string cid)
{
var customerList = new List<DtoCustomer>();
customerList = CustomerFactory.Gets();
ExcelExport.EpplusExportToExcelFromObjectList(customerList.ToList<object>(), "Customer List", true);
return null;
}
Also you can define which column with which name shows on Excel Document. you have to create an attribute class for this.
using System.Attribute;
public class ExportAttribute : Attribute
{
public string DisplayName { get; set; }
public bool IsVisible { get; set; }
}
Then, implement this attribute to your class:
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; }
}
I know you said no third-party but the reason seems to be cost.
The library I use is GemBox. It is free as long as the spreadsheets are not too large (150 rows and 5 worksheets max). For my use this is no problem and it works very well.
http://www.gemboxsoftware.com/GBSpreadsheet.htm
There are also some open source options.
If you are writing to the XML format then ExcelPackage is free (GPL) and may work for you:
http://excelpackage.codeplex.com/
If you want no XML but the other formats, I hear good things about ExcelLibrary (LGPL):
http://code.google.com/p/excellibrary/
There is also a port of the JExcel library (LGPL) to C#:
http://www.chrislaforetsoftware.com/products.html
There are built in functions for exporting an ASP.Net grid to excel. It gives a little warning message to the end user but it works.
It is described here: C Sharp Corner