對 Excel 進行編程,實際上就是通過 .Net Framework 去調(diào)用 Excel 的 COM 組件,所有要在 Web 環(huán)境下調(diào)用 COM 組件的時候,都需要對其進行相應(yīng)的配置。 很多朋友都反映在 Windows 環(huán)境下調(diào)試正常的程序,一拿到 Web 環(huán)境中就出錯,實際上就是因為缺少了這一步。 下面就詳細(xì)介紹 DCOM 的配置過程。
Dim filePath As String filePath = Server.MapPath("testFile.xls") Dim xlApp As Excel.Application Dim xlBook As Excel.Workbook Dim xlSheet As Excel.Worksheet Dim xlRange As Excel.Range Try xlApp = New Excel.Application ''不顯示Excel窗口,自動釋放,不顯示提示信息 xlApp.Visible = False xlApp.UserControl = False xlApp.DisplayAlerts = False ''打開一個作為輸出模板的文件 'xlBook = xlApp.Workbooks.Open(filePath) ''或是新建一個文件 xlBook = xlApp.Workbooks.Add() ''選擇當(dāng)前的 Sheet ''【注意】索引的下標(biāo)是從1開始的,而不是0 xlSheet = xlBook.Sheets(1) Dim strTitle As String Dim strPos As String strTitle ="大航海時代4 補給港口列表" ''選擇單元格 strPos ="A1:F1" xlRange = xlSheet.Range(strPos) ''設(shè)置單元格內(nèi)容 xlRange.Formula = strTitle ''字體:18號,粗體 xlRange.Font.Size =18 xlRange.Font.Bold = True ''合并單元格 xlRange.MergeCells = True ''設(shè)置背景色 ''使用內(nèi)置的顏色 ''xlRange.Interior.ColorIndex =40 ''或者直接設(shè)置RGB顏色 xlRange.Interior.Color = RGB(255, 204, 153) ''設(shè)置居中 xlRange.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter ''設(shè)置行高 xlRange.RowHeight =25 ''保存打開的文件 'xlBook.Save() ''保存新建的文件 xlBook.SaveAs(filePath) Catch ex As Exception Throw ex Finally ''釋放對象資源 ReleaseComObject(xlRange) ReleaseComObject(xlSheet) If Not xlBook Is Nothing Then xlBook.Close() ReleaseComObject(xlBook) End If If Not xlApp Is Nothing Then xlApp.Quit() ReleaseComObject(xlApp) End If ''強制回收內(nèi)存 GC.Collect() End Try
其中的ReleaseComObject方法:
Sub ReleaseComObject()Sub ReleaseComObject(ByVal obj AsObject) IfNot obj IsNothingThen System.Runtime.InteropServices.Marshal.ReleaseComObject(obj) obj =Nothing EndIf End Sub
將這段代碼放到你的項目中,執(zhí)行之后,你就會在 Web 項目的目錄中找到輸出的 “testFile.xls”文件。