Skip to content

Instantly share code, notes, and snippets.

@h09shais
Created January 11, 2023 13:05
Show Gist options
  • Save h09shais/0869de9e5a80d1499a061adfad9f5b99 to your computer and use it in GitHub Desktop.
Save h09shais/0869de9e5a80d1499a061adfad9f5b99 to your computer and use it in GitHub Desktop.
EPPlus ExcelPackage to Html table
public static class ExcelPackageExtension
{
internal static byte[] HtmlBytes(this ExcelPackage package)
{
string html = string.Empty;
string headerHtml = string.Empty;
string footerHtml = string.Empty;
string theadHtml = string.Empty;
const string header = "{{header}}";
const string footer = "{{footer}}";
const string thead = "{{thead}}";
html += header;
ExcelWorksheets sheets = package.Workbook.Worksheets;
foreach (ExcelWorksheet sheet in sheets)
{
if (sheet.Dimension == null) continue;
int noOfCol = sheet.Dimension.End.Column;
int noOfRow = sheet.Dimension.End.Row;
html += $"<table>{thead}<tbody>";
bool trOpen = false, theadOpen = false;
for (int i = 1; i <= noOfRow; i++)
{
string trHtml = string.Empty;
for (int j = 1; j <= noOfCol; j++)
{
int colspan = 1;
int rowspan = 1;
if (!sheet.Cells[i, j].Merge || (sheet.Cells[i, j].Merge &&
IsMergeRange(sheet.Cells[i, j].Address)))
{
if (sheet.Cells[i, j] != null && sheet.Cells[i, j].Value != null && colspan > 1)
{
if(!trOpen)
headerHtml += $"<div class='header'><h2>{sheet.Cells[i, j].Value}</h2></div>";
else
footerHtml += $"<div class='footer'>{sheet.Cells[i, j].Value}</div>";
}
if (sheet.Cells[i, j] != null && sheet.Cells[i, j].Value != null && colspan == 1)
{
trOpen = true;
trHtml += !theadOpen ? $"<th rowspan='{rowspan}' colspan='{colspan}'>" : $"<td rowspan='{rowspan}' colspan='{colspan}'>";
trHtml += sheet.Cells[i, j].Value;
trHtml += !theadOpen ? "</th>" : "</td>";
}
}
bool IsMergeRange(string address)
{
colspan = 1;
rowspan = 1;
foreach (string item in sheet.MergedCells)
{
string[] sub = item.Split(':');
if (sub.Length > 0 && sub[0].Equals(address))
{
ExcelRange range = sheet.Cells[item];
colspan = range.End.Column - range.Start.Column + 1;
rowspan = range.End.Row - range.Start.Row + 1;
return true;
}
}
return false;
}
}
if (trOpen)
{
if (!theadOpen)
{
theadHtml += $"<thead><tr>{trHtml}</tr></thead>";
theadOpen = true;
}
else
{
html += $"<tr>{trHtml}</tr>";
}
}
}
html += "</tbody></table>";
}
html += footer;
html = html.Replace(thead, theadHtml);
html = html.Replace(header, headerHtml);
html = html.Replace(footer, footerHtml);
return Encoding.ASCII.GetBytes(html);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment