C#將HTML導出Excel


首先這個 不能用ajax 操作,不過 我現在講的 這個方法和ajax 的效果一樣。

你在你需要導出的頁面寫個方法 

function DaoChu ()
{
  location.href = "DaoChu.aspx";
}

然后在 DaoChu.aspx 頁面的后台Page_Load  中 直接寫以下代碼 

 

 string html = "<table><tr><td>1</td><td>11</td></tr><tr><td>2</td><td>22</td></tr></table>";
                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\">");
                string fileCss = Server.MapPath("~/css/daoChuCSS.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>");
                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(html);//HTML
                Response.Flush();
                Response.End();

這樣 就好了 ,html 代碼 最好是table里面寫,因為EXCEL  其實就是 table 。

希望幫助到的同學 留下你寶貴的評論,謝謝

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM