【问题标题】:gridview data export to excel in asp.net在asp.net中将gridview数据导出到excel
【发布时间】:2013-04-05 11:07:57
【问题描述】:

我尝试将网格视图数据传输到 excel ......但是输出是一个空白的 excel 表。如何解决这个问题?是否有任何代码可以将网格视图值传输到带有数据库的 excel 表?

protected void btnexcel_Click1(object sender, EventArgs e)
{
    Response.Clear();
    Response.Buffer = true;
    Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls");
    Response.Charset = "";
    Response.ContentType = "application/vnd.ms-excel";

    StringWriter sw = new StringWriter();
    HtmlTextWriter hw = new HtmlTextWriter(sw);

    gvdetails.AllowPaging = false;
    gvdetails.DataBind(); 
    gvdetails.HeaderRow.Style.Add("background-color", "#FFFFFF");
    gvdetails.HeaderRow.Cells[0].Style.Add("background-color", "green");
    gvdetails.HeaderRow.Cells[1].Style.Add("background-color", "green");
    gvdetails.HeaderRow.Cells[2].Style.Add("background-color", "green");
    for (int i = 0; i < gvdetails.Rows.Count;i++ )
    {
        GridViewRow row = gvdetails.Rows[i];
        row.BackColor = System.Drawing.Color.White;
        row.Attributes.Add("class", "textmode");
        if (i % 2 != 0)
        {
            row.Cells[0].Style.Add("background-color", "#C2D69B");
            row.Cells[1].Style.Add("background-color", "#C2D69B");
            row.Cells[2].Style.Add("background-color", "#C2D69B");
        }
    }

    string style = @"<style> .textmode { mso-number-format:\@; } </style>"; 
    Response.Write(style); 

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

【问题讨论】:

  • 你在这里遇到什么错误?
  • @Ratna :正在生成的 Excel 工作表是空白的。请正确阅读要求。
  • 希望您知道这不是 excel 导出,您正在提供 html 表格并以错误的内容类型欺骗浏览器作为响应。使用这种方法可以解决许多问题。 stackoverflow.com/a/10245406/351383
  • 几乎所有的答案都在这里写一个(HtmlTextWriter)字符串或有互操作代码。两者都不要使用。这将导致您稍后在 DateTime 和 Decimal 格式方面出现问题。 Excel 也会发出警告,因为您生成的不是“真正的”Excel 文件,而是扩展名为 .xls 的 HTML 页面。开始使用专门的库来创建 Excel 文件,例如 EPPlusExample herehere.

标签: c# asp.net excel


【解决方案1】:

您的工作表是空白的,因为您的字符串编写器为空。 这可能会有所帮助

System.Web.UI.HtmlTextWriter htmlWrite =
    new HtmlTextWriter(stringWrite);

    GridView1.RenderControl(htmlWrite);

这是完整的代码

protected void Button1_Click(object sender, EventArgs e)
{
    Response.Clear();

    Response.AddHeader("content-disposition", "attachment;
    filename=FileName.xls");


    Response.ContentType = "application/vnd.xls";

    System.IO.StringWriter stringWrite = new System.IO.StringWriter();

    System.Web.UI.HtmlTextWriter htmlWrite =
    new HtmlTextWriter(stringWrite);

    GridView1.RenderControl(htmlWrite);

    Response.Write(stringWrite.ToString());

    Response.End();

}

【讨论】:

  • 如果它是一个可视化的 Web 部件并且页面中没有 form 控件怎么办?
  • 如何将此输出到电子邮件的附件中?
【解决方案2】:

export excel 中的数据绑定可能有问题。检查数据是否正确合并到网格视图。

使用此代码在 Excel 工作表中导出网格视图,并注意您必须在项目中添加 iTextSharp dll。

protected void btnExportExcel_Click(object sender, EventArgs e)
    {
        Response.Clear();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls");
        Response.Charset = "";
        Response.ContentType = "application/vnd.ms-excel";

        StringWriter sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        GridView1.AllowPaging = false;

        // Re-Bind data to GridView 

        using (CompMSEntities1 CompObj = new CompMSEntities1())
        {
            Start = Convert.ToDateTime(txtStart.Text);
            End = Convert.ToDateTime(txtEnd.Text);

            GridViewSummaryReportCategory.DataSource = CompObj.SP_Category_Summary(Start, End);
            SP_Category_Summary_Result obj1 = new SP_Category_Summary_Result();
            GridView1.DataBind();
           GridView1.Visible = true;
            ExportTable.Visible = true;
        }

        //Change the Header Row back to white color

        GridView1.HeaderRow.Style.Add("background-color", "#FFFFFF");


       GridView1.Style.Add(" font-size", "10px");




        //Apply style to Individual Cells

        GridView1.HeaderRow.Cells[0].Style.Add("background-color", "green");
        GGridView1.HeaderRow.Cells[1].Style.Add("background-color", "green");
        GridView1.HeaderRow.Cells[2].Style.Add("background-color", "green");
        GridView1.HeaderRow.Cells[3].Style.Add("background-color", "green");
        GridView1.HeaderRow.Cells[4].Style.Add("background-color", "green");

        for (int i = 1; i < GridView1.Rows.Count; i++)
        {
            GridViewRow row = GridView1.Rows[i];

            //Change Color back to white

            row.BackColor = System.Drawing.Color.White;

            //Apply text style to each Row

        //    row.Attributes.Add("class", "textmode");

            //Apply style to Individual Cells of Alternating Row

            if (i % 2 != 0)
            {
                row.Cells[0].Style.Add("background-color", "#C2D69B");
                row.Cells[1].Style.Add("background-color", "#C2D69B");
                row.Cells[2].Style.Add("background-color", "#C2D69B");
                row.Cells[3].Style.Add("background-color", "#C2D69B");
                row.Cells[4].Style.Add("background-color", "#C2D69B");
            }
        }
        GridView1.RenderControl(hw);

        //style to format numbers to string

        string style = @"<style> .textmode { mso-number-format:\@; } </style>";

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

【讨论】:

    【解决方案3】:

    我想对你有帮助

    string filename = String.Format("Results_{0}_{1}.xls", DateTime.Today.Month.ToString(), DateTime.Today.Year.ToString());
            if (!string.IsNullOrEmpty(GRIDVIEWNAME.Page.Title))
                filename = GRIDVIEWNAME.Page.Title + ".xls";
    
            HttpContext.Current.Response.Clear();
    
            HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + filename);
    
    
            HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
            HttpContext.Current.Response.Charset = "";
    
            System.IO.StringWriter stringWriter = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
    
    
    
            System.Web.UI.HtmlControls.HtmlForm form = new System.Web.UI.HtmlControls.HtmlForm();
            GRIDVIEWNAME.Parent.Controls.Add(form);
            form.Controls.Add(GRIDVIEWNAME);
            form.RenderControl(htmlWriter);
    
            HttpContext.Current.Response.Write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />");
            HttpContext.Current.Response.Write(stringWriter.ToString());
            HttpContext.Current.Response.End();
    

    【讨论】:

      【解决方案4】:

      除了做所有这些......你不能使用如下所示的更简单的方法。

      Response.ClearContent();
                  Response.AddHeader("content-disposition", "attachment; filename=" + strFileName);
                  Response.ContentType = "application/excel";
                  System.IO.StringWriter sw = new System.IO.StringWriter();
                  HtmlTextWriter htw = new HtmlTextWriter(sw);
                  gv.RenderControl(htw);
                  Response.Write(sw.ToString());
                  Response.End();
      

      你可以得到整个演练here

      【讨论】:

        【解决方案5】:

        要检查的其他内容是确保视图状态处于打开状态(我昨天刚刚解决了这个问题)。如果你没有打开 viewstate,gridview 将是空白的,直到你再次加载它。

        【讨论】:

          【解决方案6】:

          最好的方法是使用 closedxml。以下是参考链接

          https://closedxml.codeplex.com/wikipage?title=Adding%20DataTable%20as%20Worksheet&referringTitle=Documentation

          你可以简单地使用

              var wb = new ClosedXML.Excel.XLWorkbook();
          DataTable dt = GeDataTable();//refer documentaion
          
          wb.Worksheets.Add(dt);
          
          Response.Clear();
          Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
          Response.AddHeader("content-disposition", "attachment;filename=\"FileName.xlsx\"");
          
          using (var ms = new System.IO.MemoryStream()) {
              wb.SaveAs(ms);
              ms.WriteTo(Response.OutputStream);
              ms.Close();
          }
          
          Response.End();
          

          【讨论】:

          【解决方案7】:

          我没有 DataSource 对应的 gridview
          虽然您的代码中有DataBind

          gvdetails.DataBind(); 
          

          【讨论】:

          • 我认为 DataBind 在那里,就在 AllowPaging 的下方
          • 我说的是datasource?
          猜你喜欢
          • 2013-08-05
          • 1970-01-01
          • 1970-01-01
          • 2019-10-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多