我正在开发一些涉及多种形式的项目..在每种形式我必须使用下面的代码将excel导入到datagrid中...我不想复制每个表单的代码..计划创建模块以便我可以从每个表单调用函数将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
有没有办法做到这一点?。
任何建议赞赏:)
答案 0 :(得分: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()
答案 1 :(得分:0)
它看起来像你可以放入子或函数的模式,并在每次需要调用导入时进行调用:
Public Sub ImportForm()
'Import Logic
End Sub
然后在您需要的地方致电ImportForm()
。
答案 2 :(得分:0)
以下是Standard Modules in VB .NET的教程。
这将允许您在一个位置创建Excel逻辑,并从多个表单中调用它。
答案 3 :(得分:0)
我会像yparask一样创建一个函数,但是然后传递datagrid
Public Function GetExcelTable(Dgv as datagridview) AS boolean
' do your openfile and import stuff here
return true ' succesfull
return false ' unsuccesfull