ASP.NET Generate Excel 檔案 (只支援 ASCII Character Set)
Default.aspx.vb |
Private Sub Create_Excel() Dim FileName As String = Server.MapPath(".\Temp.xls") Dim xlApp As Excel.Application Dim xlWorkBook As Excel.Workbook Dim xlWorkSheet As Excel.Worksheet Dim misValue As Object = System.Reflection.Missing.Value xlApp = New Excel.ApplicationClass xlWorkBook = xlApp.Workbooks.Add(misValue) xlWorkSheet = xlWorkBook.Sheets("sheet1") Generate_SpreedSheet(xlWorkSheet) xlWorkSheet.SaveAs(FileName) xlWorkBook.Close() xlApp.Quit() ReleaseObject(xlApp) ReleaseObject(xlWorkBook) ReleaseObject(xlWorkSheet) Dim file As System.IO.FileInfo = New System.IO.FileInfo(FileName) Response.Clear() 'Response.Charset = "UTF-8" 'Response.ContentEncoding = System.Text.Encoding.UTF8 Response.AddHeader("Content-Disposition", "attachment; filename=" & Server.UrlEncode(file.Name)) Response.AddHeader("Content-Length", file.Length.ToString()) Response.ContentType = "application/ms-excel" Response.WriteFile(file.FullName) Response.End() End Sub Private Sub ReleaseObject(ByVal obj As Object) Try System.Runtime.InteropServices.Marshal.ReleaseComObject(obj) obj = Nothing Catch ex As Exception obj = Nothing Finally GC.Collect() End Try End Sub Private Sub Generate_SpreedSheet(ByRef A As Excel.Worksheet) A.Cells(1, 1) = "Team Name" A.Cells(1, 2) = "League Name" For k As Integer = 0 To GridView1.Rows.Count – 1 A.Cells(k + 2, 1) = GridView1.Rows(k).Cells(0).Text A.Cells(k + 2, 2) = GridView1.Rows(k).Cells(1).Text Next End Sub |