无法让ACE.OLEDB在datagridview中显示excel文件

时间:2013-12-18 03:09:58

标签: vb.net datagridview excel-2007 oledb

我有以下代码,我正在尝试使用OLE.DB将Excel文件加载到datagridview中。程序运行,但datagridview仍为空白。知道为什么吗?我在64x机器上运行Excel 2007,所以我将项目构建更改为x86,但它仍然无法正常工作。想法?

Public Class Records

Dim excel_app As Excel.Application
Dim workbook As Excel.Workbook
Dim sheet_name As String
Dim sheet As Excel.Worksheet
Dim ColumnCount, RowCount, TotalCellCount As Long
Dim yearstamp As String = _
    DateTime.Now.ToString("yyyy")
Dim exeDir As New IO.FileInfo(Reflection.Assembly.GetExecutingAssembly.FullName)
Dim xlPath = IO.Path.Combine(exeDir.DirectoryName, "Records.xlsx")

Public Function QueryExcel(ByVal sheet As String) As DataTable
    'use this connection string for .xlsx files
    Dim cs2007 As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=@FILENAME;Extended Properties=""Excel 12.0 Xml;HDR=YES;IMEX=1"";"

    'use this connection string for .xls files
    Dim cs2003 As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=@FILENAME;Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"";"

    Dim sql As String = String.Format("SELECT * FROM [{0}$]", sheet)
    Dim cs = cs2007.Replace("@FILENAME", IO.Path.Combine(exeDir.DirectoryName, "Records.xlsx"))
    'get contents of xls file
    Using cnn As New OleDb.OleDbConnection(cs)
        Using cmd As New OleDb.OleDbCommand(sql, cnn)
            Dim t As New System.Data.DataTable
            Try
                cnn.Open()
                t.Load(cmd.ExecuteReader)
            Catch ex As Exception
                'handle exception. in this case i'm just returning an empty table
            End Try
            Return t
        End Using
    End Using
End Function
Private Sub Records_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Dim t2013 = QueryExcel("2013")
    DataGridView1.DataSource = t2013

End Sub

0 个答案:

没有答案