gridview匯出excel檔案且把數字型別的列轉換成字元匯出(防止處理成科學計數法)
Public Function OutExcel(ByVal dt As DataTable)
HttpContext.Current.Response.Clear()
HttpContext.Current.Response.Buffer = True
HttpContext.Current.Response.Charset = "UTF-8"
Dim strFileName As String = Server.UrlEncode("查詢結果.xls")
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" & strFileName & ".xls")
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312") '設定輸出流為簡體中文
HttpContext.Current.Response.ContentType = "application/ms-excel"
Dim tw As System.IO.StringWriter = New System.IO.StringWriter()
Dim hw As HtmlTextWriter = New HtmlTextWriter(tw)
Dim gv As New GridView
gv.DataSource = dt
AddHandler gv.RowDataBound, AddressOf gv_RowDataBound
gv.DataBind()
gv.RenderControl(hw)
HttpContext.Current.Response.Write(tw.ToString())
HttpContext.Current.Response.Flush()
HttpContext.Current.Response.End()
Return True
End Function
Protected Sub gv_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
'防止處理成科學計數法
For i As Integer = 0 To e.Row.Cells.Count - 1
e.Row.Cells(i).Style.Add("mso-number-format", "/@")
Next
End If
End Sub