如何在Excel表中导出报告?

时间:2015-01-20 06:23:48

标签: c# asp.net

  private void ExportGridToExcel()
    {
        Response.Clear();
        Response.ClearHeaders();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", "attachment;filename="
   + "Excelsheet_" + DateTime.Now.Ticks.ToString() + ".xls");
        Response.Charset = "";
        Response.ContentType = "application/vnd.xls";
        StringWriter StringWriter = new System.IO.StringWriter();
        HtmlTextWriter HtmlTextWriter = new HtmlTextWriter(StringWriter);

        gvdisplay.RenderControl(HtmlTextWriter);// render gridview 
    control
        Response.Write(StringWriter.ToString());
        Response.End();

    }

如何在Excel表格中导出报告?因为它不在Excel工作表中显示? 所以给我一个回应和适当的解决方案

2 个答案:

答案 0 :(得分:1)

以下是将网格视图数据导出到Excel的代码

protected void btnExport_Click(object sender, EventArgs e)
{
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition",string.Format("attachment;filename={0}", "Customers.xls"));
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gvDetails.AllowPaging = false;
BindGridview();
//Change the Header Row back to white color
gvDetails.HeaderRow.Style.Add("background-color", "#FFFFFF");
//Applying stlye to gridview header cells
for (int i = 0; i < gvDetails.HeaderRow.Cells.Count; i++)
{
 gvDetails.HeaderRow.Cells[i].Style.Add("background-color", "#df5015");
}
gvDetails.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}

public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}

答案 1 :(得分:0)

试试这个

   Response.Clear();
        Response.AddHeader("content-disposition","attachment;filename=Excelsheet"+ DateTime.Now.Ticks.ToString() + ".xls");
        Response.Charset = "";
        Response.ContentType = "application/vnd.xls";
        StringWriter StringWriter = new System.IO.StringWriter();
        HtmlTextWriter HtmlTextWriter = new HtmlTextWriter(StringWriter);

            gvPendingRO.RenderControl(HtmlTextWriter);


        Response.Write(StringWriter.ToString());
        Response.End();
        Response.Clear();

请勿忘记覆盖此方法

public override void VerifyRenderingInServerForm(Control control)
{
    /* Confirms that an HtmlForm control is rendered for the specified ASP.NET
       server control at run time. */
}