读取
vb.net
Try
Dim ofDialog As New OpenFileDialog()
If (ofDialog.ShowDialog() = DialogResult.OK) Then
filePath = ofDialog.FileName
Else
Return
End If
If (Not File.Exists(filePath)) Then
Return
End If
Dim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0" +
"Data Source=" + filePath + "" +
"Extended Properties='Excel 8.0;HDR=NO;IMEX=1';"
Dim objConn As OleDbConnection = New OleDbConnection(strConn)
If (objConn.State <> ConnectionState.Open) Then
objConn.Open()
End If
Dim schemaTable As DataTable = objConn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables,Nothing)
Dim objCmd As OleDbCommand = New OleDbCommand("",objConn)
Dim objDA As OleDbDataAdapter = Nothing
Dim objDs As DataSet = New DataSet()
For i = 0 To schemaTable.Rows.Count
objCmd.CommandText = "SELECT * FROM [" + schemaTable.Rows(i)(2).ToString() + "]"
objDA = New OleDbDataAdapter(objCmd)
Dim objDt As DataTable = New DataTable()
objDA.Fill(objDt)
objDs.Tables.Add(objDt)
Next
Catch ex As Exception
End Try
C#.net
OpenFileDialog ofDialog = new OpenFileDialog(); if (ofDialog.ShowDialog() == DialogResult.OK) { filePath = ofDialog.FileName; } else { return; } if (!File.Exists(filePath)) { return; } //连接 String strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + filePath + ";" + "Extended Properties='Excel 8.0;HDR=NO;IMES=1'"; try { OleDbConnection objConn = new OleDbConnection(strConn); if (objConn.State != ConnectionState.Open) { objConn.Open(); } DataTable schemaTable = objConn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables,null); OleDbCommand objCmd = new OleDbCommand("",objConn); OleDbDataAdapter objDA = null; DataSet objDs = new DataSet(); for (int i = 0; i < schemaTable.Rows.Count; i++) { objCmd.CommandText = "SELECT * FROM [" + schemaTable.Rows[i][2].ToString() + "]"; objDA = new OleDbDataAdapter(objCmd); DataTable objDt = new DataTable(); objDA.Fill(objDt); objDs.Tables.Add(objDt); } } catch (Exception ex) { MessageBox.Show(ex.Message); }