using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using OfficeOpenXml; using System.IO; using EPPlus.Html; namespace testepplus { public partial class Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string zpath = Server.MapPath("/") + "test1.xlsx"; FileInfo zfile = new FileInfo(zpath); using (ExcelPackage excel = new ExcelPackage(zfile,"123")) { //excel.SaveAs(new FileInfo(Server.MapPath("/") + "test1.xlsx"), "123"); Response.Write(EPPlus.Html.EPPlusExtensions.ToHtml(excel.Workbook.Worksheets[3])); } } } }
fx要4.5+ ,需要huget package epplus ,epplus.html
可以从https://github.com/fitogram/EPPlus.Html 下载源码更改fx为4.0
epplus.html 0.20版本不支持excel里的图片
修改epplus.html添加支持图片的不成熟的源码
using EPPlus.Html.Converters; using EPPlus.Html.Html; using OfficeOpenXml; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using System.Drawing; namespace EPPlus.Html { public static class EPPlusExtensions { public static string ToHtml(this ExcelWorksheet sheet) { int lastRow = sheet.Dimension.Rows; int lastCol = sheet.Dimension.Columns; HtmlElement htmlTable = new HtmlElement("table"); htmlTable.Attributes["cellspacing"] = 0; htmlTable.Styles["white-space"] = "nowrap"; //render rows for (int row = 1; row <= lastRow; row++) { ExcelRow excelRow = sheet.Row(row); var test = excelRow.Style; HtmlElement htmlRow = htmlTable.AddChild("tr"); htmlRow.Styles.Update(excelRow.ToCss()); for (int col = 1; col <= lastCol; col++) { ExcelRange excelCell = sheet.Cells[row, col]; HtmlElement htmlCell = htmlRow.AddChild("td"); string cc = getPictureCode(row, col, sheet); if (cc == "") { htmlCell.Content = excelCell.Text; } else { htmlCell.Content = cc; } htmlCell.Styles.Update(excelCell.ToCss()); } } return htmlTable.ToString(); } public static string getPictureCode(int row ,int col , ExcelWorksheet sheet) { foreach (OfficeOpenXml.Drawing.ExcelDrawing excelDrawing in sheet.Drawings) { OfficeOpenXml.Drawing.ExcelPicture excelPicture = excelDrawing as OfficeOpenXml.Drawing.ExcelPicture; if (excelPicture.From.Column+1==col && excelPicture.From.Row+1 == row){ return "<img src = "data:image/jpeg;base64," + ImgToBase64String(excelPicture.Image) + ""/>"; } } return ""; } public static CssInlineStyles ToCSS(this ExcelStyles styles) { throw new NotImplementedException(); } public static string ImgToBase64String(Image image) { MemoryStream ms = new MemoryStream(); try { image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); byte[] arr = new byte[ms.Length]; ms.Position = 0; ms.Read(arr, 0, (int)ms.Length); return Convert.ToBase64String(arr); } catch (Exception ex) { return ""; } finally { ms.Close(); } } } }