程式如下:
Response.AddHeader("content-disposition", "attachment; filename=P.xls")
Response.ContentType = "application/vnd.ms-excel"
Dim sw As StringWriter = New System.IO.StringWriter
Dim hw As HtmlTextWriter = New HtmlTextWriter(sw)
GridView1.RenderControl(hw)
Response.Write(sw.ToString())
Response.End()
按下Button出現的錯誤在GridView1.RenderControl(hw)這一行,型別 'GridView' 的控制項 'GridView1' 必須置於有 runat=server 的表單標記之中。
解決方法
1.在程式碼中加入此副程式(MSDN用法說明):
Public Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)
'處理'GridView' 的控制項 'GridView' 必須置於有 runat=server 的表單標記之中
End Sub
2.匯出時為亂碼主要是因為轉碼沒有轉好:
在.ASPX中加入下面紅色的屬性。
<%@ Page Language="VB" ResponseEncoding="UTF-8".......%>
在程式中加入下列紅色的程式碼。
Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click
......以上略
Response.Write("<meta http-equiv=Content-Type content=text/html;charset=utf-8>")
Response.AppendHeader("Content-Disposition", "attachment; filename=P.xls")
Response.ContentType = "application/vnd.ms-excel"
GridView1.RenderControl(hw)
Response.Write(sw.ToString())
Response.End()
End Sub
3.切換到.aspx原始碼在頁頭<@ page....> 加入
EnableEventValidation = "false" AutoEventWireup="true"
沒有留言:
張貼留言