Question

I have a computer(actually several machines) on my companies network that do not have office installed. I need to develop a vb.net program that will parse information from a spreadsheet which is usually in an .xls format. I don't feel that there are many options for reading data from an .xls document without the interop. If so what are some options?

If I could even convert an .xls to .xlsx programmatically without the interop, that would be an option too. I could then use ClosedXML to parse from a xlsx. Or is there a way to read an .xls file with ClosedXML that I'm not seeing?

Any help would be great as I am having trouble finding the answer to this one.

Was it helpful?

Solution

You don't need to use com interop to read from an Excel file. You can use OleDb (although you might need to install the office data connectivity components)

Imports System.Data.OleDb:

Public Shared Function ReadExcelWorkSheet(ByVal sheetName As String, ByVal connectionString As String) As DataTable
    Dim sql As String = String.Format("SELECT * FROM [{0}$]", sheetName)
    Dim dt = New DataTable()

    Using conn As OleDbConnection = New OleDbConnection(connectionString)
        Using cmd = New OleDbCommand(sql, conn)
            conn.Open()
            Using adapter = New OleDbDataAdapter(cmd)
                adapter.Fill(dt)
            End Using
        End Using
        conn.Close()
    End Using
    Return dt
End Function

Where connection string is for xlsx files:

Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\myFolder\myExcel2007file.xlsx;Extended Properties="Excel 12.0 Xml;HDR=YES";

or for xls files:

Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\myFolder\myOldExcelFile.xls;Extended Properties="Excel 8.0;HDR=YES";

more info on the connection strings here

OTHER TIPS

You can read it via ADO.Net. I'd need to see your existing code, but this should allow you to open it without Excel.

System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\myFolder\myExcel2007file.xlsx;
Extended Properties='Excel 12.0 Xml;HDR=YES';")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top