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