1) I first had trouble with not closing the Excel.exe *32 process and solved that by using the FinalReleaseComObject(ExcelFile).
2) When I use the FinalReleaseComObject, it re-checks the "Ignore other applications that use Dynamic Data Exchange" under Excel's Options-->Advanced. Then any time I try to double-click on an Excel file, I get the error: "There was a problem sending the command to the program." Excel opens, but the worksheet I want does not. The only solution I have found to this problem is to have the DDE unchecked.
Things I've noticed:
1)If I remove the FinalReleaseComObject, the DDE problem goes away, but doesn't release the process.
2)If I use FinalReleaseComObject and already have Excel open when I export the file, the DDE remains unchecked.
Below is my code, I am just sending this sub a DataTable and a string for the FileName. Any suggestions?
Private Sub PrintTable(ByVal data As DataTable, ByVal FileName As String)
Try
Dim priorSum As Integer = 0
Dim newSum As Integer = 0
Dim xlProcID As Integer = 0
For Each proc As Process In Process.GetProcessesByName("excel")
priorSum += proc.Id
Next proc
Dim ExcelFile As New Excel.Application
Dim wBook As Excel.Workbook = ExcelFile.Workbooks.Add()
Dim wSheet As Excel.Worksheet = CType(wBook.Worksheets(1), Excel.Worksheet)
ExcelFile.Visible = False
ExcelFile.IgnoreRemoteRequests = True
ExcelFile.ErrorCheckingOptions.EvaluateToError = False
ExcelFile.DisplayAlerts = False
For Each proc As Process In Process.GetProcessesByName("excel")
newSum += proc.Id
Next proc
xlProcID = newSum - priorSum
Dim dt As System.Data.DataTable = data
Dim dc As System.Data.DataColumn
Dim dr As System.Data.DataRow
Dim colIndex As Integer = 0
Dim rowIndex As Integer = 0
For Each dc In dt.Columns
colIndex = colIndex + 1
ExcelFile.Cells(1, colIndex) = dc.ColumnName
Next
For Each dr In dt.Rows
rowIndex = rowIndex + 1
colIndex = 0
For Each dc In dt.Columns
colIndex = colIndex + 1
ExcelFile.Cells(rowIndex + 1, colIndex) = dr(dc.ColumnName)
Next
Next
wSheet.Columns.AutoFit()
Dim strFileName As String = "C:\Temp\" & FileName & "_" & DateTime.Now.ToString("yyyy-MM-dd") & ".xlsx"
Dim blnFileOpen As Boolean = False
Try
Dim fileTemp As System.IO.FileStream = System.IO.File.OpenWrite(strFileName)
fileTemp.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
blnFileOpen = False
End Try
If System.IO.File.Exists(strFileName) Then
System.IO.File.Delete(strFileName)
End If
wBook.SaveAs(strFileName)
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(wSheet)
wBook.Close(SaveChanges:=False)
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(wBook)
ExcelFile.Quit()
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(ExcelFile)
ShowMSG("Your file has been saved in your C:\Temp folder.", "Export successful", 1, "")
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub

New Topic/Question
Reply



MultiQuote



|