Excel表到数据表

时间:2015-04-16 11:07:34

标签: vb.net datatable import-from-excel

我正在尝试将整个Excel表格添加到数据表中并声明如下变量:

workbook = APP.Workbooks.Open(fileString)
worksheet = workbook.Worksheets("Report")

能够从Excel文件中读取。我已使用消息框进行了检查:

MsgBox(worksheet.Cells(1, 1).Value)

这样可行,但我找不到将Excel文件中的值添加到数据表中的方法:

Dim table As New DataTable

table.Columns.Add("DATE")
table.Columns.Add("VALUE")

任何人都可以帮我吗?

2 个答案:

答案 0 :(得分:1)

您可以使用某些库来执行此操作 例如NPOI(example)或Epplus(example) 或use OleDb provider

答案 1 :(得分:1)

您可以使用oledb

将Excel导出到datatable

注意:

  

因为我们要使用oledb连接,所以我们必须进口   System.Data.OleDb

尝试以下代码

Dim dt As New DataTable
        dt.Columns.Add("date")
        dt.Columns.Add("value")
        Dim dr As DataRow = dt.NewRow()
        Time = System.DateTime.Now
        Try
            XLDbConnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\name.xls;Extended Properties=""Excel 8.0;IMEX=1;HDR=YES;""") 'give your file path in source
        Catch ex As Exception
            Throw (ex)
            Exit Sub
        End Try
        XLDbConnection.Open()
        Try
            XLDbCommand = New OleDbCommand("select * from [sheet1$]", XLDbConnection) 'sheet1 is name of the excel sheet
            XLDbDataReader = XLDbCommand.ExecuteReader
        Catch ex As Exception

            Throw (ex)
            Exit Sub
        End Try
        If XLDbDataReader.HasRows = True Then
            'Assign excel data to datacolumn of our datatable
            While XLDbDataReader.Read
                Try
                    dr("date") = XLDbDataReader.Item("date").ToString() 'column name as it is in excel file 
                    dr("value") = XLDbDataReader.Item("value").ToString()
                    dt.Rows.Add(dr)
                Catch ex As Exception
                    Throw (ex)
                End Try
            End While
        End If

希望这会有所帮助