gpt4 book ai didi

.net - 在.net中正确关闭excel interop应用程序时出现问题

转载 作者:行者123 更新时间:2023-12-04 18:15:02 26 4
gpt4 key购买 nike

我在.net中与Office excel互操作时遇到问题。我已经尝试了很多方法来关闭自己创建的要在程序中使用的excel应用程序,工作簿和工作表,但是我始终注意到excel.exe仍在内存中。我什至尝试强制垃圾收集器,请帮忙。

这是我用来实例化所有内容的代码:

Private mExcelApp As Microsoft.Office.Interop.Excel.ApplicationClass
Private mWorkBook As Microsoft.Office.Interop.Excel.Workbook
Private mWorkSheet As Microsoft.Office.Interop.Excel.Worksheet


Public Sub Execute()

mExcelApp = New Microsoft.Office.Interop.Excel.ApplicationClass
If mFirstPass Then
mWorkBook = mExcelApp.Workbooks.Add()
mWorkSheet = CType(mWorkBook.ActiveSheet(), Microsoft.Office.Interop.Excel.Worksheet)
Else
mWorkBook = mExcelApp.Workbooks.Open(System.IO.Path.Combine(mFileLocation, mMTDefinition.Description & "_" & mMTDefinition.Version & ".xls"))
mWorkSheet = CType(mWorkBook.Sheets(1), Microsoft.Office.Interop.Excel.Worksheet)
Dim excelRange As Microsoft.Office.Interop.Excel.Range = mWorkSheet.UsedRange
excelRange.SpecialCells(Microsoft.Office.Interop.Excel.XlCellType.xlCellTypeLastCell).Activate()
mCurrentRow = mExcelApp.ActiveCell.Row + 1

End If

Here is how i try to close everything

If mFirstPass Then
mWorkBook.SaveAs(System.IO.Path.Combine(mFileLocation, mMTDefinition.Description & "_" & mMTDefinition.Version & ".xls"))
mFirstPass = False
Else
mWorkBook.Save()
End If
a
mWorkBook.Close()
mExcelApp.Quit()

mWorkSheet = Nothing
mWorkBook = Nothing
mExcelApp = Nothing
System.GC.Collect()

最佳答案

基本思想是为每个创建的COM对象调用Marshal.ReleaseComObject。

    Dim app As New Excel.Application()
Dim workBook As Excel.Workbook = app.Workbooks.Add()
Try

Dim t As Int32 = 0
' This example is filling an excel spreadsheet using data stored in a Dictionary
For Each key In sampleData.Keys
t += 1
' Add a worksheet and dump data.
Dim sheet As Excel.Worksheet = workBook.Worksheets.Add()
sheet.Name = key

' Set columns
For i = 1 To sampleData(key).Columns.Count
sheet.Cells(1, i) = sampleData(key).Columns(i - 1).ColumnName
Next

' Set data.
For r = 1 To sampleData(key).Rows.Count
For c = 1 To sampleData(key).Columns.Count
sheet.Cells(r + 1, c) = sampleData(key).Rows(r - 1).Item(c - 1).ToString()
Next c
Next r
Marshal.ReleaseComObject(sheet)
Next

workBook.SaveAs("fileName.xls", Excel.XlFileFormat.xlExcel8)
workBook.Close(SaveChanges:=False)

Finally
app.Quit()
Marshal.ReleaseComObject(workbook)
Marshal.ReleaseComObject(app)
app = Nothing
End Try

关于.net - 在.net中正确关闭excel interop应用程序时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5115602/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com