Opening an excel file and launching excel
Hey everyone,
My question is that I saved a file in vb.net to excel using the SaveFileDialog and now I want to launch the excel program and open that file after the user saves it. Can anyone help me with this? Thank you in advance. Some of my code is below. I was thinking about doing it with a temporary file name such as highlighted below my code.
Code:
Dim oExcel As Object
Dim oBook As Object
Dim oSheet As Object
oExcel = CreateObject("Excel.Application")
oBook = oExcel.Workbooks.Add
oSheet = oBook.Worksheets(1)
''Save To Excel
Dim sfd As New SaveFileDialog()
sfd.FileName = mTitle
sfd.Filter = "*.xlsx|*.xlsx" 'xml
sfd.ShowDialog()
oBook.SaveAs(sfd.FileName())
'Quit Excel
oExcel.Quit()
Dim fn As String = My.Computer.FileSystem.GetTempFileName
My.Computer.FileSystem.WriteAllText(fn, s.ToString, False)
Dim pi As New ProcessStartInfo
pi.FileName = "Notepad.exe"
pi.Arguments = fn
pi.WindowStyle = ProcessWindowStyle.Normal
Process.Start(pi)
Re: Opening an excel file and launching excel
So what's the problem? You seem to have it all worked out except for using notepad instead of Excel?
Re: Opening an excel file and launching excel
Here is an example using early binding (you can adapt as needed for late binding) that creates the Excel file based on a SaveDialog then open the file by setting xlApp.Visible = True. Disposal of the Excel objects is done when the user closes Excel.
Code:
Private Sub cmdCreateFileDemo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdCreateFileDemo.Click
If SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
CreateFile(SaveFileDialog1.FileName, True)
End If
End Sub
Code to create the Excel file. Note if the file exists for this example we don't try to overwrite it but by removing the check you can overwrite it but you should also know that if the file exists and is open the code will throw an exception. This can easily by remedied if you need to work this out too.
Code:
Public Sub CreateFile(ByVal FileName As String, ByVal ShowMessageBox As Boolean)
If Not IO.File.Exists(FileName) Then
If ShowMessageBox Then
MessageBox.Show("Creating '" & FileName & "'")
End If
Dim xlApp As Excel.Application = Nothing
Dim xlWorkBooks As Excel.Workbooks = Nothing
Dim xlWorkBook As Excel.Workbook = Nothing
xlApp = New Excel.Application
xlApp.DisplayAlerts = False
xlWorkBooks = xlApp.Workbooks
xlWorkBook = xlWorkBooks.Add()
xlWorkBook.SaveAs(FileName)
xlApp.Visible = True
End If
End Sub