I am trying to modify exisiting excel worksheet. Precisely I'd like to add a few rows to a table that exists in the worksheet (created using format as a table). I tried
var table = sheet.Tables["PositionsTable"];
but the 'table' thus created is only a meta-data of the actual table, and I can not add rows to it. If I try
sheet.Cells[table.Address.Address.ToString()].LoadFromCollection(positions);
Then I don't get the formatting of the table.
Anyone knows how I add rows to the table! Thanks
EPPlus supports multiple properties of spreadsheets like cell ranges, cell styling, charts, pictures, shapes, comments, tables, protection, encryption, pivot tables, data validation, conditional formatting, formula calculation, etc. First of all install EPPlus using Packet Manager console by writing the following command:
Yes this can be done with EPPlus. You can use Dimension if you do not have fixed rows/columns.
EPPlus is a very helpful open-source 3rd party DLL for writing data to excel. EPPlus supports multiple properties of spreadsheets like cell ranges, cell styling, charts, pictures, shapes, comments, tables, protection, encryption, pivot tables, data validation, conditional formatting, formula calculation, etc.
First of all install EPPlus using Packet Manager console by writing the following command: Let’s see how to create and write to an excel-sheet using C#. In this program, we are taking static values for the Articles data but in real-time, we can use database call and foreach loop for iteration of each record.
We use something like the following at our company. Basically the idea is that for each record you want to output you create an object array of the data to load into excel and then call LoadFromArrays.
using (var excelPkg = new ExcelPackage())
{
var name = "Sheet1";
//You will probably pass the columns to output into this function
var headerArray = new string[] { "Column1", "Column2" };
var data = positions
.Select(i => headerArray.Select(h => GetValue(i, h)).ToArray());
var ws = excelPkg.Workbook.Worksheets.Add(name);
ws.Cells["A1"].LoadFromArrays(
((object[])headerArray).ToSingleItemEnumerable().Union(data));
ws.Row(1).Style.Font.Bold = true; //set header to bold
excelPkg.SaveAs(stream, "password");
}
private static object GetValue(Position item, string field)
{
//Your logic goes here
return null;
}
public static IEnumerable<T> ToSingleItemEnumerable<T>(this T o)
{
yield return o;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With