首页 > 代码库 > 第十二篇 C# 将HTML 直接转成Excel

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

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