0

我正在做一些涉及许多表格的项目..在每个表格中我必须使用下面的代码将excel导入数据网格..我不想复制每个表格的代码..计划创建模块以便我可以调用每个表单的功能将 excel 数据导入 datagrid 。

   Try
            With Form1.OpenFileDialog1
                .Title = "Please open the STM_Ticket_Template"
                .Filter = "Excel Files | *.xlsx"
                If .ShowDialog = Windows.Forms.DialogResult.OK Then
                    Dim fn1 As String = .FileName.ToString
                    Dim oledbCon As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + fn1 + ";Extended Properties=Excel 12.0;"
                    conDB = New OleDb.OleDbConnection(oledbCon)
                    adap = New OleDb.OleDbDataAdapter("Select * From [SAM_TICKETS$]", conDB)
                    adap.TableMappings.Add("Table", "Excel")
                    dSet = New DataSet
                    adap.Fill(dSet)
                    Me.DataGridView1.DataSource = dSet.Tables(0)
                End If
            End With
            Dim msg As String = MsgBox("Template successfully loaded", MsgBoxStyle.Information, "Creation Template")
        Catch ex As Exception
            MsgBox("Load Error..." + Environment.NewLine + ex.ToString)
        End Try 

有什么办法可以做到这一点?

任何建议表示赞赏:)

4

4 回答 4

1

你可能有一个功能:

Imports System.Windows.Forms


Public Function GetExcelTable() AS DataTable
    Dim od As OpenFileDialog = new OpenFileDialog
    od.ShowDialog
    try
        With od
                .Title = "Please open the STM_Ticket_Template"
                .Filter = "Excel Files | *.xlsx"
                If .ShowDialog = Windows.Forms.DialogResult.OK Then
                    Dim fn1 As String = .FileName.ToString
                    Dim oledbCon As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + fn1 + ";Extended Properties=Excel 12.0;"
                    conDB = New OleDb.OleDbConnection(oledbCon)
                    adap = New OleDb.OleDbDataAdapter("Select * From [SAM_TICKETS$]", conDB)
                    adap.TableMappings.Add("Table", "Excel")
                    dSet = New DataSet
                    adap.Fill(dSet)
                    Return dSet.Tables(0)
                End If
            End With
            Dim msg As String = MsgBox("Template successfully loaded", MsgBoxStyle.Information, "Creation Template")
        Catch ex As Exception
            MsgBox("Load Error..." + Environment.NewLine + ex.ToString)
        End Try 
End Function

然后将其称为:

Me.DataGridView1.DataSource = GetExcelTable()
于 2013-08-02T13:12:59.583 回答
0

它看起来像是一种模式,您可以将其放入子或函数中,并在每次需要调用导入时进行调用:

Public Sub ImportForm()
'Import Logic
End Sub

然后ImportForm()在你需要的地方打电话。

于 2013-08-02T13:12:16.833 回答
0

这是关于VB .NET 中标准模块的教程。

这将允许您在一个地方创建 Excel 逻辑并从多个表单中调用它。

于 2013-08-02T13:15:04.687 回答
0

我会创建一个像 yparask 一样的函数,然后传递数据网格

Public Function GetExcelTable(Dgv as datagridview) AS boolean

' do your openfile and import stuff here

return true ' succesfull

return false ' unsuccesfull
于 2013-08-02T14:48:02.877 回答