0

我正在使用以下功能将我的数据导出到 Excel 表:

string filename = "Test.xls"; 
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);

//Get the H`enter code here`TML for the control.
yourGrid.RenderControl(hw);
//Write the HTML back to the browser.
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");

    Response.Write(tw.ToString());

但未创建 excel 工作表。尽管它在 chrome 浏览器底部显示 excel 正在下载。当它完成下载时,我点击它,它说文件无法打开。请建议我有什么问题?

[编辑]

 Response.Clear();
 Response.Buffer = true;
 //use Response.AddHeader
 Response.AddHeader("content-disposition", "attachment;filename=Test.xlsx");
 Response.Charset = "";
 Response.ContentType = "application/vnd.ms-excel";
 StringWriter sw = new StringWriter();
 HtmlTextWriter hw = new HtmlTextWriter(sw);
 gvLogs.RenderControl(hw);
 gvLogs.AllowPaging = false;
 gvLogs.DataBind(); // bind data 
 Response.Output.Write(sw.ToString());
 //need to call Flush and End methods 
 Response.Flush();
 Response.End();

给出同样的错误

4

4 回答 4

0

Epplus是一个很好的 excel 导入/导出库。你可以检查一下。

于 2013-07-24T07:25:28.020 回答
0

检查下面的代码

Response.Clear();
Response.Buffer = true;
//use Response.AddHeader
Response.AddHeader("content-disposition", "attachment;filename=Test.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.xls";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.RenderControl(hw);
GridView1.AllowPaging = false;
GridView1.DataBind(); // bind data 
Response.Output.Write(sw.ToString());
//need to call Flush and End methods 
Response.Flush();
Response.End();
于 2013-07-24T07:18:31.263 回答
0

更改Response.ContentType代码中的“”值,如下所示。

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

希望这会帮助你。

于 2013-07-24T10:36:56.637 回答
0

你可以试试这个

 private void ExportToExcel(DataTable dt)
    {
        if (dt.Rows.Count > 0)
        {
            string filename = "DownloadReport.xls";
            System.IO.StringWriter tw = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
            DataGrid dgGrid = new DataGrid();
            dgGrid.DataSource = dt;
            dgGrid.DataBind();

            //Get the HTML for the control.
            dgGrid.RenderControl(hw);
            //Write the HTML back to the browser.
            Response.ContentType = "application/vnd.ms-excel";
            Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");
            this.EnableViewState = false;
            Response.Write(tw.ToString());
            Response.End();
        }
    }
于 2013-07-24T07:26:34.057 回答