专家,请让我知道我能做到这一点的最佳方法......
我正在开发一个 VB.Net 应用程序,该应用程序使用 Microsoft.Office.Interop.Excel 对象库在工作簿中创建工作表并在这些工作表中创建数据透视表。
我的代码看起来像这样:
Dim ExcelApp As New Microsoft.Office.Interop.Excel.Application
Dim wbk As Microsoft.Office.Interop.Excel.Workbook = Nothing
Dim wksRawData As Microsoft.Office.Interop.Excel.Worksheet = Nothing
Dim wksPvtTbl As Microsoft.Office.Interop.Excel.Worksheet = Nothing
Dim pvtCache As Microsoft.Office.Interop.Excel.PivotCache = Nothing
Dim pvtTables As Microsoft.Office.Interop.Excel.PivotTables = Nothing
Dim pvtTable As Microsoft.Office.Interop.Excel.PivotTable = Nothing
Dim r1 As Microsoft.Office.Interop.Excel.PivotField = Nothing
Dim r2 As Microsoft.Office.Interop.Excel.PivotField = Nothing
Dim df1 As Microsoft.Office.Interop.Excel.PivotField = Nothing
Try
... Create the objects, put in the information
Catch ex As Exception
MessageBox.Show("There was an error creating the Excel file", "Error Creating File", MessageBoxButtons.OK)
Finally
ReleaseObject(r1)
ReleaseObject(r2)
ReleaseObject(df1)
ReleaseObject(pvtTable)
ReleaseObject(pvtTables)
ReleaseObject(pvtCache)
ReleaseObject(wksRawData)
ReleaseObject(wksPvtTbl)
ReleaseObject(wbk)
ExcelApp.DisplayAlerts = True
ExcelApp.Quit()
ReleaseObject(ExcelApp)
ExcelApp = Nothing
wbk = Nothing
wksRawData = Nothing
GC.Collect()
End Try
然后我的发布对象的代码如下所示:
Public Sub ReleaseObject(ByRef Reference As Microsoft.Office.Interop.Excel.Application)
Dim i As Integer
If Reference IsNot Nothing Then
i = System.Runtime.InteropServices.Marshal.ReleaseComObject(Reference)
While i > 0
i = System.Runtime.InteropServices.Marshal.ReleaseComObject(Reference)
End While
Reference = Nothing
End If
End Sub
Public Sub ReleaseObject(ByRef Reference As Microsoft.Office.Interop.Excel.Workbook)
Dim i As Integer
If Reference IsNot Nothing Then
i = System.Runtime.InteropServices.Marshal.ReleaseComObject(Reference)
While i > 0
i = System.Runtime.InteropServices.Marshal.ReleaseComObject(Reference)
End While
Reference = Nothing
End If
End Sub
... etc
我知道这类问题有很多解决方案,但我迷失在所有不同的解决方案中,不知道什么最适合我目前的情况……这是一个很好的方法吗?如果不是,什么是更有效的方法??
谢谢!!!