zoukankan      html  css  js  c++  java
  • 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();

            }

        }

     

  • 相关阅读:
    比尔盖茨,乔布斯,扎克伯格,Linus 等巨佬的办公桌
    快速从 Windows 切换到 Linux 环境
    海外开发者账号上架总结
    Chrome 浏览器对标签进行整理和分组的功能太棒了!
    最受嵌入式软件工程师青睐的系统
    我最喜欢的云 IDE 有哪些?
    前端zip包下载
    el-upload上传组件(隐藏上传按钮/隐藏文件删除标记)
    滚动条样式
    使用ul标签制作简单的菜单(vue模板)
  • 原文地址:https://www.cnblogs.com/yumianhu/p/3707541.html
Copyright © 2011-2022 走看看