对 Excel 进行编程,实际上就是通过 .Net Framework 去调用 Excel 的 COM 组件,所有要在 Web 环境下调用 COM 组件的时候,都需要对其进行相应的配置。 很多朋友都反映在 Windows 环境下调试正常的程序,一拿到 Web 环境中就出错,实际上就是因为缺少了这一步。 下面就详细介绍 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() ''选择当前的 Sheet ''【注意】索引的下标是从1开始的,而不是0 xlSheet = xlBook.Sheets(1) Dim strTitle As String Dim strPos As String strTitle ="大航海时代4 补给港口列表" ''选择单元格 strPos ="A1:F1" xlRange = xlSheet.Range(strPos) ''设置单元格内容 xlRange.Formula = strTitle ''字体:18号,粗体 xlRange.Font.Size =18 xlRange.Font.Bold = True ''合并单元格 xlRange.MergeCells = True ''设置背景色 ''使用内置的颜色 ''xlRange.Interior.ColorIndex =40 ''或者直接设置RGB颜色 xlRange.Interior.Color = RGB(255, 204, 153) ''设置居中 xlRange.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter ''设置行高 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 ''强制回收内存 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
将这段代码放到你的项目中,执行之后,你就会在 Web 项目的目录中找到输出的 “testFile.xls”文件。
现在,我们将整个过程的关键部分提出来,就简化为下面这样的结构:
[定义Excel对象] Try [使用Excel对象] Catch ex As Exception Throw ex Finally [释放Excel对象] [强制回收内存] EndTry