获取特定的excel(.xls)单元格

时间:2019-02-06 09:18:39

标签: vb.net

是否可以使用此代码在excel中获取特定的单元格?。

 Try

        OpenFileDialog.InitialDirectory = "Desktop"
        OpenFileDialog.Filter = "All Files (*.*)|*.*|Excel Files (*.xlsx)|*.xlsx|Xls Files (*.xls)|*.xls"

        If OpenFileDialog.ShowDialog(Me) = System.Windows.Forms.DialogResult.OK Then
            Dim fi As New IO.FileInfo(OpenFileDialog.FileName)
            Dim Filename As String = OpenFileDialog.FileName
            excel = fi.FullName
            conn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excel + ";Extended Properties=Excel 12.0;")
            dta = New OleDbDataAdapter("select * from [Sheet1$]", conn)
            dts = New DataSet
            dta.Fill(dts, "Sheet1$")
            DGV1.DataSource = dts
            DGV1.DataMember = "Sheet1$"
            conn.Close()

        End If
        lblRowCount.Text = DGV1.Rows.Count - 1
    Catch ex As Exception
        MsgBox(ex.Message)
        conn.Close()
        Exit Sub

    End Try

或者还有其他方法可以使用逐个插入单元格的循环将excel文件导入到datagridview中。

1 个答案:

答案 0 :(得分:1)

您可以使用此代码打印C2单元格值

'--------  Option Strict off ---------------
    Private Sub Button13_Click(sender As Object, e As EventArgs) Handles Button13.Click
                Dim mypath As String
                Dim xlApp As New Excel.Application
                Dim wb As Excel.Workbook
                Dim ws As Excel.Worksheet
                mypath = "F:\Documents\myfile.xlsx"
                wb = xlApp.Workbooks.Open(mypath)
                ws = xlApp.Worksheets(1)
                MessageBox.Show(ws.cells(2, 3).value + " in cell C2")
                wb.Close()
                xlApp.Quit()
        End Sub
    ' --------- option strict on ------------------
    Private Sub Button13_Click(sender As Object, e As EventArgs) Handles Button13.Click
        Dim percorso As String
        Dim xlApp As New Excel.Application
        Dim wb As Excel.Workbook
        Dim ws As Excel.Worksheet
        mypath = "F:\Documents\myfile.xlsx"
        wb = xlApp.Workbooks.Open(mypath)
        ws = CType(xlApp.Worksheets(1), Excel.Worksheet)
        Dim xRng As Excel.Range = CType(ws.Cells(2, 3), Excel.Range)
        Dim val As Object = xRng.Value()
        MessageBox.Show(val.ToString + " in cell C2")
        wb.Close()
        xlApp.Quit()
    End Sub