使用asp.net导出到excel
本文关键字:excel asp net 使用 | 更新日期: 2023-09-27 18:24:32
我使用以下函数将数据导出到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();
给出相同的错误
Epplus是一个很好的excel导入/导出库。你可以去看看。
你可以试试这个
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();
}
}
按如下方式更改代码中的"Response.ContentType
"值。
Response.ContentType = "application/vnd.xls";
希望这对你有帮助。
检查以下代码
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();