第十二篇 HTML 直接转成Excel
前些天写项目的时候,客户要求用HTML表格把信息展示出来,后面还要用展示的内容要导出Excel。本来想想在后台操作的话估计是要做死了,但是经过细想,Excel能够发布成HTML,一定可以由HTML转成Excel。经过几次搜索,算是把问题完善解决了代码如下:
1 Response.ContentType = "application/force-download"; 2 Response.AddHeader("content-disposition", 3 "attachment; filename=" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls"); 4 Response.Write("<html xmlns:x=\"urn:schemas-microsoft-com:office:excel\">"); 5 Response.Write("<head>"); 6 Response.Write("<META http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">"); 7 8 9 #region 样式的读取 10 11 string fileCss = Server.MapPath("~/Content/CalCSS/tableCss.css"); 12 string cssText = string.Empty; 13 StreamReader sr = new StreamReader(fileCss); 14 var line = string.Empty; 15 while ((line = sr.ReadLine()) != null) 16 { 17 cssText += line; 18 } 19 sr.Close(); 20 Response.Write("<style>" + cssText + "</style>"); 21 22 #endregion 23 24 Response.Write("<!--[if gte mso 9]><xml>"); 25 Response.Write("<x:ExcelWorkbook>"); 26 Response.Write("<x:ExcelWorksheets>"); 27 Response.Write("<x:ExcelWorksheet>"); 28 Response.Write("<x:Name>Report Data</x:Name>"); 29 Response.Write("<x:WorksheetOptions>"); 30 Response.Write("<x:Print>"); 31 Response.Write("<x:ValidPrinterInfo/>"); 32 Response.Write("</x:Print>"); 33 Response.Write("</x:WorksheetOptions>"); 34 Response.Write("</x:ExcelWorksheet>"); 35 Response.Write("</x:ExcelWorksheets>"); 36 Response.Write("</x:ExcelWorkbook>"); 37 Response.Write("</xml>"); 38 Response.Write("<![endif]--> "); 39 40 Response.Write(strHtml1);//这里是前台页面的HTML 41 42 Response.Flush(); 43 Response.End();
经过测试能够完全的展示页面的样式和规格:
前台HTML:
生成后的HTML:
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。