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

标签 asp.net-mvc export-to-excel

我在将数据导出到 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-mvc - 使用 ASP.NET MVC 4 C# 将数据导出到 Excel 文件正在呈现到 View 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16346227/

相关文章:

java - 将数据写入单元格并写入一行

c# - 使用颜色代码从 Gridview 导出到 excel

sql-server - 如何将sql server中的海量数据导出到excel文件中

Laravel EXCEL 和 PDF 导出

.net - ASP.NET MVC 中的用户身份验证和授权

asp.net-mvc - Azure OpenID 通过 OWIN 中间件连接导致无限重定向循环

javascript - 如何在Firefox中干净地停止网页?

php - 使用 PHP 将图像添加到 excel 文件

c# - ASP.NET 中的 JavaScript 脚本

c# - 通过 VS 2015 RC 进行非 Azure 部署