Allowing VB.NET app to convert Excel Files to Datatable

后端 未结 2 1663
我在风中等你
我在风中等你 2021-01-22 08:46

My VB.NET app currently allows me to convert CSV files to a datatable thanks to the code provided by David in this question I posted: Previous Question

Now I am trying t

相关标签:
2条回答
  • 2021-01-22 09:24

    Use can use the following connection string for .xlsx file. I have used it and working fine.

    P_FIle = ( File Name with path )
    
    P_Con_Str = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & P_File & ";Extended Properties=""Excel 12.0 XML;HDR=Yes;"""
    
    0 讨论(0)
  • 2021-01-22 09:31

    I think that the error is that from the connection string and the OLEDB Command:

    ConnectionString

    You don't have to use IO.Path.GetDirectoryName(path) it returns the directory name, you have to provide the file full path:

    con.ConnectionString = String.Format("Provider={0};Data Source={1};Extended Properties=""Excel 12.0 XML;HDR=Yes;""", "Microsoft.ACE.OLEDB.12.0", path)
    

    Refer to this link for excel connectionstring generation function: import data from excel 2003 to dataTable

    OLEDB Command

    You must provide the Worksheet name in the Command instead of the Filename:

     Using cmd As OleDb.OleDbCommand = New OleDb.OleDbCommand("SELECT * FROM [Sheet1$]" , con)
    

    If the Sheet names is dynamic and you have to get the first sheet in the excel file:

    Dim dbSchema as DataTable = con.GetOleDbSchemaTable (OleDbSchemaGuid.Tables, null)
    
    Dim firstSheetname as String = dbSchema.Rows(0)("TABLE_NAME").ToString
    Using cmd As OleDb.OleDbCommand = New OleDb.OleDbCommand("SELECT * FROM [" & firstSheetname & "]" , con)
    

    References

    • Reading from excel using oledbcommand
    • Read and Write Excel Documents Using OLEDB
    0 讨论(0)
提交回复
热议问题