将Excel工作表数据读入DataTable或Dataset

时间:2016-01-30 09:13:06

标签: asp.net .net vb.net excel dataset

我尝试从Excel导入数据集并发生错误消息。

我正在研究这个网站http://vb.net-informations.com/excel-2007/vb.net_excel_oledb.htm

x >= 0

2 个答案:

答案 0 :(得分:0)

你可以使用免费软件第三方EPPLUS。它可以将excel文件导入到数据集中,它还有很多功能可以操作excel文件

答案 1 :(得分:0)

首先我相信你的连接不正确,你有一个xlsx文件,但连接是为xls设置的。

BTW不确定这是一个表单还是asp项目,但确实看起来像是一个窗口的表单项目,正在思考你的第一个指示asp.net的标签。

关于如何设置连接字符串,是否只想阅读,表格中的第一行是否有列名称或数据,列中是否有混合数据等,Excel可能会非常棘手。

以下是我用来通过连接简化操作的片段,但预先警告它并非万无一失,因为您需要在连接中正确设置HDR和IMEX,

Imports System.Data.OleDb

Module ExcelOleDbConnections
    ''' <summary>
    ''' Creates a connection string on read data from an excel file
    ''' </summary>
    ''' <param name="FileName"></param>
    ''' <param name="Header">Yes if first row is column-names, No if first row is data</param>
    ''' <param name="IMEX"></param>
    ''' <returns></returns>
    ''' <remarks>
    ''' See following page for clarification on extended properties
    ''' including IMEX. Ignore C# code.
    ''' http://www.codeproject.com/Articles/37055/Working-with-MS-Excel-xls-xlsx-Using-MDAC-and-Oled
    ''' </remarks>
    <System.Diagnostics.DebuggerStepThrough()> _
    Public Function ExcelConnectionString(
        ByVal FileName As String,
        Optional ByVal Header As String = "No",
        Optional ByVal IMEX As Integer = 1) As String

        Dim Builder As New OleDbConnectionStringBuilder
        If IO.Path.GetExtension(FileName).ToUpper = ".XLS" Then
            Builder.Provider = "Microsoft.Jet.OLEDB.4.0"
            Builder.Add("Extended Properties", String.Format("Excel 8.0;IMEX={0};HDR={1};", IMEX, Header))
        Else
            Builder.Provider = "Microsoft.ACE.OLEDB.12.0"
            Builder.Add("Extended Properties", String.Format("Excel 12.0;IMEX={0};HDR={1};", IMEX, Header))
        End If

        Builder.DataSource = FileName

        Return Builder.ToString

    End Function
End Module

读取第一行是数据的工作表的示例。注意我使用的是可选参数,因此后两个使用默认值

Dim dt As New DataTable

' sheet has data in first row
Using cn As New OleDb.OleDbConnection With {.ConnectionString = ExcelConnectionString(Loc)}
    Using cmd As New OleDb.OleDbCommand With {.Connection = cn, .CommandText = "select * from [Sheet1$]"}
        cn.Open()
        dt.Load(cmd.ExecuteReader)
    End Using
End Using

此示例我们假设第一行是字段/列名称

Dim dt As New DataTable

' sheet has column names for first row
Using cn As New OleDb.OleDbConnection With {.ConnectionString = ExcelConnectionString(Loc, "Yes", 0)}
    Using cmd As New OleDb.OleDbCommand With {.Connection = cn, .CommandText = "select * from [Sheet1$]"}
        cn.Open()
        dt.Load(cmd.ExecuteReader)
    End Using
End Using

填充DataGridView

If dt.Rows.Count > 0 Then
    DataGridView1.DataSource = dt
Else
    '
    ' recover e.g. tell user there are no records in this sheet
    '
End If

一起示例

Try
    Dim Loc As String = IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Param\exceldata.xlsx")
    If IO.File.Exists(Loc) Then
        Dim dt As New DataTable

        ' sheet has column names for first row
        Using cn As New OleDb.OleDbConnection With {.ConnectionString = ExcelConnectionString(Loc, "Yes", 0)}
            Using cmd As New OleDb.OleDbCommand With {.Connection = cn, .CommandText = "select * from [Sheet1$]"}
                cn.Open()
                dt.Load(cmd.ExecuteReader)
            End Using
        End Using


        If dt.Rows.Count > 0 Then
            DataGridView1.DataSource = dt
        Else
            '
            ' recover e.g. tell user there are no records in this sheet
            '
        End If
    End If

Catch ex As Exception
    MessageBox.Show("TODO")
End Try

查看我的Windows窗体示例(是的,我在标签中看到了asp.net) Excel and OleDb basics to advance operations