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

前端之家收集整理的这篇文章主要介绍了asp.net-mvc – 使用ASP.NET MVC导出数据到Excel文件4 C#正在呈现到视图中前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我无法将数据导出到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");
    }

猜你在找的asp.Net相关文章