I need to improve performance of the code that maps datatable to excel spreadsheet.
The old code loops through the datatable and creates excel. I created a timer too print out the time it takes to generate the report for this approach:
var watch = System.Diagnostics.Stopwatch.StartNew();
System.Data.DataTable dt = new System.Data.DataTable();
dt = (System.Data.DataTable)Session["ISOReport"];
TableCell td;
TableRow tr;
HyperLink a;
TableHeaderRow thr;
TableHeaderCell thc;
thr = new TableHeaderRow();
thr.BorderStyle = BorderStyle.Solid;
thr.BorderColor = System.Drawing.Color.White;
for (int i = 0; i < dt.Columns.Count; i++)
{
thc = new TableHeaderCell();
thc.Text = dt.Columns[i].ColumnName;
thr.Cells.Add(thc);
}
tblReport.Rows.Add(thr);
for (int j = 0; j < dt.Rows.Count; j++)
{
tr = new TableRow();
tr.BorderStyle = BorderStyle.Solid;
tr.BorderColor = System.Drawing.Color.White;
for (int i = 0; i < dt.Columns.Count; i++)
{
td = new TableCell();
td.Text = dt.Rows[j][i].ToString();
tr.Cells.Add(td);
}
tblReport.Rows.Add(tr);
}
watch.Stop();
var elapsedMs = watch.ElapsedMilliseconds;
lblInfo.Text = ReportName + " Generation Time: " + elapsedMs.ToString();
Then, I created another method using EPPlus approach:
private void NewExport(string name, System.Data.DataTable dt)
{
//DataSet ds = (DataSet)Session["DSIsoReport"];
var watch = System.Diagnostics.Stopwatch.StartNew();
using (pck = new ExcelPackage())
{
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Demo");
ws.Cells["A5"].LoadFromDataTable(dt, true);
ws.DefaultColWidth = 25;
int totalRow = ws.Dimension.End.Row;
int totalCol = ws.Dimension.End.Column;
var startCell = (ExcelRangeBase)ws.Cells["A5"];
var endCell = startCell.Offset(0,0,1,totalCol);
var headerCell = ws.Cells[endCell.ToString()];
headerCell.Style.Fill.PatternType = ExcelFillStyle.Solid;
headerCell.Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.BurlyWood);
var headerFont = headerCell.Style.Font;
headerFont.Bold = true;
watch.Stop();
var elapsedMs = watch.ElapsedMilliseconds;
ws.Cells["A4"].LoadFromText(name + " Generation Time: " + elapsedMs.ToString());
}
}
I have a REnder
method that actually is responsible for generating excel spreadsheet out of the aspx
page:
protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
Response.AddHeader("content-disposition", "inline;filename=" + ReportName + ".xls");
Response.ContentType = "application/vnd.ms-excel";
//Response.BinaryWrite(pck.GetAsByteArray());
base.Render(writer);
}
When running the application and generating the report with old way with looping, elapsed time is 355
But when using the EPPlus, elapsed time is 1676.
Looks like EPPlus is taking much longer time to execute.
From what I researched I thought EPPlus is efficient.
Is there any way to improve the code?