第十二篇 C# 將HTML 直接轉成Excel,

來源:互聯網
上載者:User

第十二篇 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:



相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.