Private Sub readexcel()
Dim cnn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & txtFileName.Text & "; Extended Properties=Excel 12.0;")
Dim oconn As New OleDbCommand("select * from [Sheet1$]", cnn)
cnn.Open()
Dim adp As New OleDbDataAdapter(oconn)
Dim dt As New DataTable()
Dim ds As DataSet
adp.Fill (dt)
dgvExcelData.SelectionMode = DataGridViewSelectionMode.FullRowSelect
dgvExcelData.EditMode = DataGridViewEditMode.EditProgrammatically
dgvExcelData.DataSource = dt
End Sub
上面的代码将Excel读入Grid View,但有些数据会丢失。有人可以告诉我为什么吗?
答案 0 :(得分:2)
默认情况下,ACE读取前8行数据并使用它来确定每列的数据类型。
如果列中这8行中的数据属于同一类型,则假定该类型,否则默认情况下将采用文本。在8列之后,它不会检查它。
如果您的列具有混合数据类型,则您必须在注册表中进行少量更改。
转到
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Office\14.0\Access Connectivity Engine\Engines\Excel
并将密钥TypeGuessRows
的值从8
更改为0
现在测试下面的代码
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
Dim strCon As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & txtFileName.Text &
"; Extended Properties=""Excel 12.0 XML;HDR=YES;IMEX=1;"""
Dim cnn As New OleDbConnection(strCon)
Dim oconn As New OleDbCommand("select * from [Sheet1$]", cnn)
cnn.Open()
Dim adp As New OleDbDataAdapter(oconn)
Dim dt As New DataTable()
adp.Fill(dt)
dgvExcelData.SelectionMode = DataGridViewSelectionMode.FullRowSelect
dgvExcelData.EditMode = DataGridViewEditMode.EditProgrammatically
dgvExcelData.DataSource = dt
End Sub
这是输出