A. Kriel
A. Kriel

Reputation: 260

Format a Excel Sheet as a Table using EPPlus

I have a .NET Core application, and I'm new to using the EPPlus library with C#.

I have a data table filled with data which I'm currently inserting into an Excel sheet using EPPlus.

I was wondering if there is a way to format the sheet as a table after you added the data to the sheet and not before?

(Like when you are using the "Format as table" function in Excel)

Sample of my code which only fills the Excel sheet:

var excelWorkSheet = excel.Workbook.Worksheets["WorkSheet1"];

using (SqlDataReader dr = cmd.ExecuteReader())
{
    dt.Load(dr);
}

excelWorkSheet.Cells["A1"].LoadFromDataTable(dt, true);

excel.SaveAs(df);

Please keep in mind the df variable above is of type file directory, and that the data in the data-table will be different for each user so the size will never be the same for two users.

Upvotes: 8

Views: 11790

Answers (1)

VDWWD
VDWWD

Reputation: 35564

Yes this can be done with EPPlus. You can use Dimension if you do not have fixed rows/columns.

using OfficeOpenXml.Table;


ExcelWorksheet ws = excel.Workbook.Worksheets[1];

//create a range for the table
ExcelRange range = ws.Cells[1, 1, ws.Dimension.End.Row, ws.Dimension.End.Column];

//add a table to the range
ExcelTable tab = ws.Tables.Add(range, "Table1");

//format the table
tab.TableStyle = TableStyles.Medium2;

Upvotes: 21

Related Questions