Vb.NET读取Excel缺失的数据
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,但一些数据将丢失。 有人能告诉我为什么吗?
默认情况下,ACE读取前8行数据,并用它来决定每列的数据types。
如果列中这8行中的数据是相同的types,那么假设该types,否则默认情况下它将采用文本。 8列之后,它不检查它。
如果你的列有混合的数据types,那么你将不得不在registry中做一些小的改动。
去
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Office\14.0\Access Connectivity Engine\Engines\Excel
并将TypeGuessRows
键的TypeGuessRows
从8
更改为0
现在testing下面的代码
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
这是输出