伊莉討論區

標題: VB.NET無法產生EXCEL檔 [打印本頁]

作者: 天兵才子    時間: 2015-2-22 08:43 AM     標題: VB.NET無法產生EXCEL檔

提示: 作者被禁止或刪除 內容自動屏蔽
作者: Jeepluo    時間: 2015-2-24 04:52 PM

輸出時不是檔名一樣就可以了,以下是我很久以前寫的提供你參考一下
  1.    Public Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)
  2.         'Confirms that an HtmlForm control is rendered for the specified ASP.NET
  3.         ' server control at run time. */
  4.         ' 我是不知這函數做什麼用, 但還不能少了這個部份
  5.     End Sub

  6.     Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click
  7.         Dim dDate As String = Replace(FormatDateTime(Now, 2), "/", "")
  8.         ' 匯出的檔名, 不能用中文哦!會變亂碼
  9.         Dim PrnFileName As String = "LogType-" & Replace(FormatDateTime(Now, 2), "/", "") & ".xls"
  10.         ' --- Excel 輸出的部份 -----------------------------------------------------------------------
  11.         Response.Clear()
  12.         Response.AddHeader("content-disposition", "attachment;filename=" & PrnFileName)
  13.         Response.Charset = "BIG5"
  14.         Response.ContentEncoding = System.Text.Encoding.GetEncoding("BIG5")
  15.         Response.Cache.SetCacheability(HttpCacheability.NoCache)
  16.         Response.ContentType = "application/vnd.ms-excel"
  17.         Dim stringWrite As System.IO.StringWriter = New System.IO.StringWriter()
  18.         Dim htmlWrite As System.Web.UI.HtmlTextWriter = New HtmlTextWriter(stringWrite)
  19.         '-----------------------------------------------------------------------------------------------
  20.         ' 讀取另一個已有的SqlDateSource 的設定
  21.         Dim sds As New SqlDataSource(Me.SqlDataSource2.ConnectionString, "")
  22.         sds.SelectCommand = Me.SqlDataSource2.SelectCommand
  23.         sds.DataSourceMode = SqlDataSourceMode.DataSet

  24.         Dim dv As Data.DataView = sds.Select(New DataSourceSelectArguments)
  25.         ' 啟動 GridView
  26.         Me.GridViewToExcel.DataSource = dv
  27.         Me.GridViewToExcel.DataBind()

  28.         ' --- Excel 輸出的部份 -----------------------------------------------------------------------
  29.         Me.GridViewToExcel.RenderControl(htmlWrite)
  30.         Response.Write(stringWrite.ToString())
  31.         Response.End()
  32.         '-----------------------------------------------------------------------------------------------

  33.     End Sub
複製代碼





歡迎光臨 伊莉討論區 (http://aaa.eyny.com/) Powered by Discuz!