2013-08-02 62 views
0

我正在处理一些涉及许多形式的项目......在每个表单中,我必须使用下面的代码将excel导入到datagrid中..我不想复制每个表单的代码。 。计划创建模块,以便我可以从每个窗体调用函数将excel数据导入到datagrid中。避免在vb.net中重复编码

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() 
+0

看起来像什么我期望:),我会试一试,让你知道状态.. –

+0

上面的代码可能不是100%准备就绪。您可能需要在Function参数列表中包含oledbCon和其他一些内容。但我想你明白了我的意思。 –

+0

正如预期的那样,代码完美地工作。我根据自己的需要做了一些更改。感谢您的时间:)祝您有个美好的一天 –

0

看起来你可以放入一个子或函数,并相互调用需要调用的导入时间的模式:

Public Sub ImportForm() 
'Import Logic 
End Sub 

然后调用ImportForm()无处不在你需要它。

+0

是的,你是对的..我知道该方法肯定会工作..对于每一个我需要导入excel数据到不同的datagrid(前datagridview1,datagridview2,.....),如何做到这一点 –

0

这里是Standard Modules in VB .NET的教程。

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

0

像yparask确实我会创建一个函数,但通过数据网格

Public Function GetExcelTable(Dgv as datagridview) AS boolean 

' do your openfile and import stuff here 

return true ' succesfull 

return false ' unsuccesfull