我正试图在VB.NET应用程序中编写一个模块,但它无法正常工作。我正在尝试创建一个数据网格视图,并加载一个excel文件到其中。然而,excel没有加载到其中。
下方的代码
Imports Microsoft.Office
Imports Microsoft.Office.Interop
Imports System.Data.OleDb
Imports System.Net.Mail
Module m_IslsHpPtSplit
Dim UploadFilePath As String
Dim UploadFileName As String
Dim dgv1 As DataGridView
Dim dgv2 As DataGridView
Public Sub LoadFile()
dgv1 = New DataGridView
dgv2 = New DataGridView
Try
Dim filedialog As OpenFileDialog = New OpenFileDialog()
Dim path As String
filedialog.Title = "Select file"
filedialog.InitialDirectory = "Desktop"
filedialog.RestoreDirectory = True
If filedialog.ShowDialog() = Windows.Forms.DialogResult.OK Then
path = filedialog.FileName
Else
path = Nothing
End If
UploadFilePath = filedialog.FileName
UploadFileName = System.IO.Path.GetFileName(filedialog.FileName)
Dim dtSheet1 As New DataTable
If Not path = Nothing Then
Using cn As New System.Data.OleDb.OleDbConnection
Dim Builder As New OleDbConnectionStringBuilder With _
{ _
.DataSource = path, _
.Provider = "Microsoft.ACE.OLEDB.12.0" _
}
Builder.Add("Extended Properties", "Excel 12.0; IMEX=1;HDR=Yes;")
cn.ConnectionString = Builder.ConnectionString
cn.Open()
Using cmd As OleDbCommand = New OleDbCommand With {.Connection = cn}
cmd.CommandText = "SELECT * FROM [FNAC$]"
Dim dr As System.Data.IDataReader = cmd.ExecuteReader
dtSheet1.Load(dr)
dgv1.DataSource = dtSheet1
End Using
End Using
MessageBox.Show(dgv1.RowCount)
MessageBox.Show("Done")
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
SplitFile()
End Sub 'LoadFile
之后,我需要进行一些计算等,但线
MessageBox.Show(dgv1.RowCount)
实际返回0。excel文件中有316行。如何获取数据以坚持使用新的dgv?
我认为问题源于没有实际将dgv1添加到任何控件集合(数据源已附加,但实际上没有创建要显示的行)。如果你使用MessageBox.Show(dtSheet1.Rows.Count)
,你可能会注意到一个计数证明数据正在被读入。我在Messagebox.Show(dgv1.RowCount)
之前添加了Form1.Controls.Add(dgv1)
,并生成了一个正确的计数。