跳到主要內容

[ASP.net] Export Gridview to Excel but missing '0' GridView匯出excel 遺漏開頭數字0



在ASP.net要用Gridview匯出excel在之前的文章中有提到過 是很簡單的一個方法
但是匯出來的excel有些全都是數字的文字儲存格都會被視為數字所以開頭的0會被去掉
尤其是向手機號碼這種資料,更是麻煩

對於這個問題,只要在程式碼中加上
Dim strStyle As String = "<style>td{mso-number-format:\@;}</style>"
然後再輸出的StringWriter
設定 WriteLine(strStyle)
這樣就行了
完整的Code如下

Dim strExportFilename As String = "ExportedData"
Response.Clear()
  Response.AddHeader("content-disposition", "attachment;filename=" + strExportFilename + ".xls")
  Response.Cache.SetCacheability(HttpCacheability.NoCache)
  Response.ContentType = "application/vnd.xls"
  Response.Charset = "big5"
  Dim strStyle As String = "<style>td{mso-number-format:\@;}</style>"
  Dim stringWrite As New System.IO.StringWriter
  Dim htmlWrite As New HtmlTextWriter(stringWrite)
  stringWrite.WriteLine(strStyle)
  GridView1.RenderControl(htmlWrite)
  Response.Write(stringWrite.ToString().Replace("<div>", "").Replace("</div>", ""))
Response.End()

 
 

留言