加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 使用ASP.NET MVC导出数据到Excel文件4 C#正在呈

发布时间:2020-12-15 18:48:55 所属栏目:asp.Net 来源:网络整理
导读:我无法将数据导出到Excel。以下似乎将gridview渲染到我的View中,而不是提示用户使用我在我的机器上安装的Excel进行打开。 Public ActionResult ExportToExcel(){ var products = this.Repository.Products.ToList(); var grid = new GridView(); grid.DataS
我无法将数据导出到Excel。以下似乎将gridview渲染到我的View中,而不是提示用户使用我在我的机器上安装的Excel进行打开。
Public ActionResult ExportToExcel()
{            
    var products = this.Repository.Products.ToList();

    var grid = new GridView();
    grid.DataSource = from p in products
                      select new
                      {
                          Id = p.Id,Name = p.Name
                      };
    grid.DataBind();

    Response.ClearContent();
    Response.Buffer = true;
    Response.AddHeader("content-disposition","attachment; filename=MyExcelFile.xls");
    Response.ContentType = "application/ms-excel";

    Response.Charset = "";
    StringWriter sw = new StringWriter();
    HtmlTextWriter htw = new HtmlTextWriter(sw);

    grid.RenderControl(htw);

    Response.Output.Write(sw.ToString());
    Response.Flush();
    Response.End();

    return View("MyView"); 
}

我究竟做错了什么?

解决方法

我已经尝试了你的代码,它的工作正常。
该文件正在创建没有任何问题,这是我使用的代码(这是你的代码,我只是更改了数据源进行测试):
public ActionResult ExportToExcel()
    {
        var products = new System.Data.DataTable("teste");
        products.Columns.Add("col1",typeof(int));
        products.Columns.Add("col2",typeof(string));

        products.Rows.Add(1,"product 1");
        products.Rows.Add(2,"product 2");
        products.Rows.Add(3,"product 3");
        products.Rows.Add(4,"product 4");
        products.Rows.Add(5,"product 5");
        products.Rows.Add(6,"product 6");
        products.Rows.Add(7,"product 7");


        var grid = new GridView();
        grid.DataSource = products;
        grid.DataBind();

        Response.ClearContent();
        Response.Buffer = true;
        Response.AddHeader("content-disposition","attachment; filename=MyExcelFile.xls");
        Response.ContentType = "application/ms-excel";

        Response.Charset = "";
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);

        grid.RenderControl(htw);

        Response.Output.Write(sw.ToString());
        Response.Flush();
        Response.End();

        return View("MyView");
    }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读