这是代码。但Excel文件显示整个aspx页面而不是gridview。
Protected Sub btnExport_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExport.Click
Try
Response.Clear()
Response.AddHeader("content-disposition", ("attachment;filename=HotelList_" & DateTime.Now.Year.ToString().Trim()) + DateTime.Now.Month.ToString().Trim().PadLeft(2, Convert.ToChar("0")) + DateTime.Now.Day.ToString().Trim().PadLeft(2, Convert.ToChar("0")) & ".xls")
Response.Charset = ""
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.ContentType = "application/vnd.ms-excel"
Dim stringWrite As New System.IO.StringWriter
Dim htmlWrite As System.Web.UI.HtmlTextWriter = New HtmlTextWriter(stringWrite)
Dim selctedCountry As String = ddlCountry.SelectedItem.Text.ToString()
Dim selCity As String = ddlCity.SelectedItem.Text.ToString()
htmlWrite.Write("<div style='PADDING-RIGHT: 5px; PADDING-LEFT: 5px; PADDING-BOTTOM: 0px; PADDING-TOP: 0px'><h3>HOTEL LIST</h3>")
htmlWrite.Write("<table><tr><td colspan='2'> Country : " & selctedCountry & " </td></tr>")
htmlWrite.Write("<table><tr><td colspan='2'> City : " & selCity & " </td></tr>")
gvHotelMarkup.RenderControl(htmlWrite)
htmlWrite.Write("</div>")
Response.Write(stringWrite.ToString())
Response.End()
Catch ex As Exception
lblErrMessage.Message = ex.Message()
End Try
End Sub
知道如何解决这个问题吗? 提前谢谢。
答案 0 :(得分:0)
我不确定究竟是什么问题但是当我将其添加到代码隐藏时它完美无缺
Public Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)
' Confirms that an HtmlForm control is rendered for the specified ASP.NET
' server control at run time.
End Sub
答案 1 :(得分:0)
Downoad ClosedXML Library
using ClosedXML.Excel;
using System.IO;
using System.Data;
Protected Sub btnExport_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExport.Click
DataTable dt = new DataTable("GridView_Data");
foreach(TableCell cell in GridView1.HeaderRow.Cells)
{
dt.Columns.Add(cell.Text);
}
foreach (GridViewRow row in GridView1.Rows)
{
dt.Rows.Add();
for (int i=0; i<row.Cells.Count; i++)
{
dt.Rows[dt.Rows.Count - 1][i] = row.Cells[i].Text;
}
}
using (XLWorkbook wb = new XLWorkbook())
{
wb.Worksheets.Add(dt);
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=GridView.xlsx");
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
}