MVC下用C#實現Excel導出


Aspx頁面腳本:

function exportxls() {

            window.open("/Common/HomeExport?startdate=" + $("#hidStartTime").val(), "exportxls", null);

        }



C#代碼如下:

   public class CommonController

    {

        public void HomeExport()

        {

            StringBuilder sHtml = new StringBuilder(string.Empty);

            //下面這句解決中文亂碼

            sHtml.Append("<meta http-equiv=content-type content=application/ms-excel; charset=utf-8/>");

            ……

            //打印表頭

            sHtml.Append("<table border=1 width=100%>");

            //打印列名

            sHtml.Append("<tr height=20 align=centerstyle='background-color:yellow'><td>No. </td><td>Project</td><td>Content</td>tr>");

            //循環讀取List集合

            ……

            //打印表尾

            sHtml.Append("</table>");

            string filename = "Report";

            //調用輸出Excel表的方法

            ExportToExcel("application/ms-excel", filename + ".xls", sHtml.ToString());

        }

 

        public void ExportToExcel(string FileType, string FileName, string ExcelContent)

        {

            System.Web.HttpContext.Current.Response.Charset = "UTF-8";

            System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;

            System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8).ToString());

            System.Web.HttpContext.Current.Response.ContentType = FileType;

            System.IO.StringWriter tw = new System.IO.StringWriter();

            System.Web.HttpContext.Current.Response.Output.Write(ExcelContent.ToString());

            System.Web.HttpContext.Current.Response.Flush();

            System.Web.HttpContext.Current.Response.End();

        }

    }

 

 


免責聲明!

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



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