Question

How can I open a tab delimited .txt file in Excel from VB.NET code?

This question has been asked on many forums, but I can not find an answer anywhere that actually solves this problem.

Dim fileName As String = "file.txt"
Dim filePath As String = System.Reflection.Assembly.GetExecutingAssembly().Location
Dim fullFilePath As String = filePath.Substring(0, filePath.LastIndexOf("\"c)) & "\" & fileName

Public Sub OpenFileInExcel()

    Process.Start("excel.exe", fullFilePath)

End Sub
Was it helpful?

Solution

Just use Process.Start() and pass "excel.exe" as the first parameter, and the filename as the second parameter:

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    Dim TabDelimitedFileName As String = "C:\Users\Mike\Documents\somefile.txt"
    If System.IO.File.Exists(TabDelimitedFileName) Then
        Process.Start("excel.exe", Chr(34) & TabDelimitedFileName & Chr(34))
    Else
        MessageBox.Show(TabDelimitedFileName, "File Not Found")
    End If
End Sub

OTHER TIPS

You can use an Excel COM object to open the file and autofit the columns:

   Dim X As New Microsoft.Office.Interop.Excel.Application()
            X.Workbooks.Open(FileNm)
            Dim W As Microsoft.Office.Interop.Excel.Worksheet = X.ActiveSheet
            Dim R As Microsoft.Office.Interop.Excel.Range = W.Range(W.Cells(1, 1), W.Cells(65000, 250))
            R.Columns.AutoFit()
            X.Visible = True
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top