2016年12月5日 星期一

[ASP.NET] 匯出EXCEL 內容中文亂碼

在ASP.net 網頁中匯出EXCEL檔案時,遇上有的user匯出中文變成了亂碼


原始程式碼:
 Protected Sub ExportExcel(sender As Object, e As EventArgs) Handles btnExcel.Click

        Dim filename As String = Format(Today.Date, "yyyyMMddHHmm")
        Response.Clear()
        Response.Buffer = True
        Response.AddHeader("content-disposition", "attachment;filename=" & filename & ".xls")
        Response.Charset = ""
        Response.ContentType = "application/vnd.ms-excel"
        Dim sw As New StringWriter()
        Dim hw As New HtmlTextWriter(sw)
        Repeater1.RenderControl(hw)
        Response.Output.Write(sw.ToString())
        Response.Flush()
        Response.End()

    End Sub


修改後程式碼:
    Protected Sub ExportExcel(sender As Object, e As EventArgs) Handles btnExcel.Click

        Dim filename As String = Format(Today.Date, "yyyyMMddHHmm")
        Response.Clear()
        Response.Buffer = True
        Response.AddHeader("content-disposition", "attachment;filename=" & filename & ".xls")
        Response.Charset = "BIG5"
Response.Write("<meta http-equiv=Content-Type content=text/html;charset=BIG5>")
Response.ContentEncoding = System.Text.Encoding.GetEncoding("BIG5")
        Response.ContentType = "application/vnd.ms-excel"
        Dim sw As New StringWriter()
        Dim hw As New HtmlTextWriter(sw)
        Repeater1.RenderControl(hw)
        Response.Output.Write(sw.ToString())
        Response.Flush()
        Response.End()

    End Sub

轉出後正常囉!