2013-10-10 141 views
0

這是代碼。但Excel文件顯示的是整個aspx頁面而不是gridview。將Gridview導出到Excel,但整個aspx頁面導出代替

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

我不知道到底是什麼問題,但是當我加入這代碼隱藏它完美

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 
+0

您好,感謝回答。我添加了這個,但它仍然導出整個頁面。 – user2621831

0

Downoad ClosedXML圖書館

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(); 
    } 
}