用户注册



邮箱:

密码:

用户登录


邮箱:

密码:
记住登录一个月忘记密码?

发表随想


还能输入:200字
云代码 - vb代码库

excel操作

2016-01-05 作者:洗车人举报

[vb]代码库

Imports System.Data.OleDb
Public Class Form1
   Private _FilePath As String = ""
   Private _DS As DataSet
   Private Const _Connectstring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=<FilePath>;Extended Properties=""Excel 8.0"""
   Private Const _SelectData = "Select * from [<TableName>$]"
   Private Sub TSBSelectFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TSBSelectFile.Click
      Me.OFDExcel.FileName = _FilePath
      If Not Me.OFDExcel.ShowDialog(Me) = vbOK Then
         Exit Sub
      End If
      _FilePath = Me.OFDExcel.FileName
      Me.TSLFilePath.Text = _FilePath
      Try
         Using cn As OleDb.OleDbConnection = New OleDbConnection(_Connectstring.Replace("<FilePath>", _FilePath))
            cn.Open()
            _DS = New DataSet
            Dim tb As DataTable = cn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
            Me.TSCBOSheetList.Items.Clear()
            For Each r As DataRow In tb.Rows
               If r("TABLE_TYPE") = "TABLE" Then
                  Me.TSCBOSheetList.Items.Add(r("TABLE_NAME").ToString.Replace("$", ""))
               End If
            Next
            If Me.TSCBOSheetList.Items.Count > 0 Then
               Me.TSCBOSheetList.SelectedIndex = 0
            End If
         End Using
      Catch ex As Exception
         MsgBox(ex.Message)
      End Try
   End Sub
 
   Private Sub TSCBOSheetList_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TSCBOSheetList.SelectedIndexChanged
      Try
         Dim TBName As String = Me.TSCBOSheetList.SelectedItem.ToString
         If _DS.Tables.Contains(TBName) Then
            Me.DataGridView1.DataSource = _DS.Tables(TBName)
            Exit Sub
         End If
         Using cn As OleDb.OleDbConnection = New OleDbConnection(_Connectstring.Replace("<FilePath>", _FilePath))
            cn.Open()
            Dim sql As String = _SelectData.Replace("<TableName>", TBName)
            Using ad As OleDbDataAdapter = New OleDbDataAdapter(sql, cn)
               ad.Fill(_DS, TBName)
               Me.DataGridView1.DataSource = _DS.Tables(TBName)
            End Using
         End Using
      Catch ex As Exception
         MsgBox(ex.Message)
      End Try
   End Sub
End Class


分享到:
更多

网友评论    (发表评论)

共1 条评论 1/1页

发表评论:

评论须知:

  • 1、评论每次加2分,每天上限为30;
  • 2、请文明用语,共同创建干净的技术交流环境;
  • 3、若被发现提交非法信息,评论将会被删除,并且给予扣分处理,严重者给予封号处理;
  • 4、请勿发布广告信息或其他无关评论,否则将会删除评论并扣分,严重者给予封号处理。