【问题标题】:ASP.NET Gridview to Export to ExcelASP.NET Gridview 导出到 Excel
【发布时间】:2022-01-12 16:31:45
【问题描述】:

我正在使用 Visual Studio 2015、Entity Framework 6 和 C#。

我正在尝试让我的 gridview 导出到 excel。我想我拥有一切,但是当单击按钮时,我的 gridview 消失了,并且没有任何内容进入文件。

我的网格视图是:

gvExOr

Excel 导出代码为:

  public partial class _Default : Page
  {
    private void BindFiles()
    {
        DirectoryInfo di = new DirectoryInfo(tbPath.Text);
        gvExOr.DataSource = di.GetFiles();
        try {
            gvExOr.DataBind();
        }
        catch { }
    }
    protected void btnExportToExcel_Click(object sender, EventArgs e)
    {
        ExportToExcel();
    }
    //Export to Excel from a GridView
    protected void ExportToExcel()
    {
        Response.Clear();
        Response.Buffer = true;
        Response.ContentType = "application / vnd.ms - excel";
        Response.AddHeader("content - disposition", "attachment; filename = MyFiles.xls");
        Response.Charset = "";
        this.EnableViewState = false;

        System.IO.StringWriter sw = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw); 
        gvExOr.RenderControl(htw);
        Response.Write(sw.ToString());
        Response.End(); 
     }
    public override void VerifyRenderingInServerForm(Control control)
    {
    }   
    protected void Page_Load(object sender, EventArgs e)
    {   
      BindFiles();
    }
  }

如何让gridview导出到excel?

【问题讨论】:

    标签: c# asp.net


    【解决方案1】:

    看起来你使用了这篇文章中的代码https://stackoverflow.com/a/10412559/5786449

    我尝试了该帖子中的示例,它对我有用。我能看到的唯一区别是您的Response.ContentTypeResponse.AddHeader。尝试去掉这些参数中的空格:

    Response.ContentType = "application/vnd.ms-excel";
    Response.AddHeader("content-disposition", "attachment;filename=MyFiles.xls");
    

    还有一点,您的代码实际上并没有为您提供 Excel 电子表格。它只是写出 GridView HTML 标记。许多 Excel 程序在 XLS 文件中不需要 HTML,并且在打开文件时会抛出错误。如果您想要一个实际的 Excel 电子表格,我建议您查看 EPPlus http://epplus.codeplex.com/ 等实用程序

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多