码迷,mamicode.com
首页 > Web开发 > 详细

第十二篇 HTML 直接转成Excel

时间:2014-12-16 13:27:51      阅读:258      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   ar   io   color   os   sp   for   

    前些天写项目的时候,客户要求用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:

    bubuko.com,布布扣  

生成后的HTML:

   bubuko.com,布布扣

    

第十二篇 HTML 直接转成Excel

标签:style   blog   http   ar   io   color   os   sp   for   

原文地址:http://www.cnblogs.com/OceanHeaven/p/4166831.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!