将数据导出到与ASP.NET MVC 4 C#的Excel文件被渲染到视图 [英] Export data to Excel file with ASP.NET MVC 4 C# is rendering into view

查看:87
本文介绍了将数据导出到与ASP.NET MVC 4 C#的Excel文件被渲染到视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法将数据导出到Excel中。下面似乎呈现GridView的到我的视图,而不是提示用户使用Excel,而我已经安装在我的机器上打开。

I am having trouble exporting data to Excel. The following seems to render the gridview into my View, instead of prompting the user to open with Excel, which I have installed on my machine.

 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"); 
}

我在做什么错了?

What am I doing wrong?

推荐答案

我想你的code和它工作得很好。
正在没有任何问题,创建的文件,这是code我用(这是你的code,我只是改变了数据源进行测试):

I have tried your code and it works just fine. The file is being created without any problem, this is the code I used (it's your code, I just changed the datasource for testing):

    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");
    }

这篇关于将数据导出到与ASP.NET MVC 4 C#的Excel文件被渲染到视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆