码迷,mamicode.com
首页 > Windows程序 > 详细

第十二篇 C# 将HTML 直接转成Excel

时间:2014-12-28 17:00:19      阅读:396      评论:0      收藏:0      [点我收藏+]

标签:

    前些天写项目的时候,客户要求用HTML表格把信息展示出来,后面还要用展示的内容要导出Excel。本来想想在后台操作的话估计是要做死了,但是经过细想,Excel能够发布成HTML,一定也可以由HTML转成Excel。经过几次搜索,算是把问题完善解决了代码如下(不能用Ajax调用来完成,因为Ajax不会刷新页面):


   

            Response.ContentType = "application/force-download";
            Response.AddHeader("content-disposition",
                "attachment; filename=" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls");
            Response.Write("<html xmlns:x=\"urn:schemas-microsoft-com:office:excel\">");
            Response.Write("<head>");
            Response.Write("<META http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">");


            #region 样式的读取

            string fileCss = Server.MapPath("~/Content/CalCSS/tableCss.css");
            string cssText = string.Empty;
            StreamReader sr = new StreamReader(fileCss);
            var line = string.Empty;
            while ((line = sr.ReadLine()) != null)
            {
                cssText += line;
            }
            sr.Close();
            Response.Write("<style>" + cssText + "</style>");

            #endregion

            Response.Write("<!--[if gte mso 9]><xml>");
            Response.Write("<x:ExcelWorkbook>");
            Response.Write("<x:ExcelWorksheets>");
            Response.Write("<x:ExcelWorksheet>");
            Response.Write("<x:Name>Report Data</x:Name>");
            Response.Write("<x:WorksheetOptions>");
            Response.Write("<x:Print>");
            Response.Write("<x:ValidPrinterInfo/>");
            Response.Write("</x:Print>");
            Response.Write("</x:WorksheetOptions>");
            Response.Write("</x:ExcelWorksheet>");
            Response.Write("</x:ExcelWorksheets>");
            Response.Write("</x:ExcelWorkbook>");
            Response.Write("</xml>");
            Response.Write("<![endif]--> ");

            Response.Write(strHtml1);//这里是前台页面的HTML

            Response.Flush();
            Response.End();

经过测试能够完全的展示页面的样式和规格:

 前台HTML:

技术分享

下载后的Excel:

技术分享


第十二篇 C# 将HTML 直接转成Excel

标签:

原文地址:http://blog.csdn.net/fw199006/article/details/42214369

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