• 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();

            }

        }

     

  • 相关阅读:
    用户调查报告
    beta冲刺总结
    beta冲刺第七天
    beta冲刺第六天
    beta冲刺第五天
    beta冲刺第四天
    beta冲刺第三天
    beta冲刺第二天
    beta冲刺第一天
    简单的密码管理器(Python)(待完善)
  • 原文地址:https://www.cnblogs.com/yumianhu/p/3707541.html
Copyright © 2020-2023  润新知