Excel シートを datagridview にインポートしようとしていますが、「データベースまたはオブジェクトは読み取り専用です」というエラーが発生します。ただし、参照しているブックには読み取り専用属性が適用されていません。そうは言っても、アプリケーションが実行されている場合、接続しているワークブックは既に開いているため、これがこのエラーに遭遇した理由であると思われます。ワークブックが開いているため、データセットを入力しようとすると、システムには読み取り専用として表示されます。
私はこの仮定で正しいですか?接続先のワークブックが開いている場合、OleDB 接続を使用して Excel シートを datagridview にインポートする方法はありますか? そうでない場合、シートを大規模にループすることなく、このデータグリッドビューにデータを入力する他の方法はありますか? 私のコードは次のとおりです。
Try
'connect to Excel data source and set gridview equal to dataset (entire sheet should be visible in gridview)
Dim MyConnection As System.Data.OleDb.OleDbConnection
Dim MyCommand As System.Data.OleDb.OleDbDataAdapter
Dim connstring As String = "Provider=Microsoft.ACE.OLEDB.12.0;" & "Data Source=" & StatVar.workbookName & ";Extended Properties=""Excel 12.0;HDR=YES;Readonly=False"";" 'may need to use different MS provider and lower OLEDB for .xls files (Microsoft.Jet.OLEDB4.0...Excel 8.0) kind of sketchy though
MyConnection = New System.Data.OleDb.OleDbConnection(connstring) 'create a new data connection to Excel data source
MyCommand = New System.Data.OleDb.OleDbDataAdapter("select * from [Budget$]", MyConnection) 'query the sheet - select all data
MyCommand.TableMappings.Add("Table", "Table") 'map data selection as table
StatVar.DtSet1 = New System.Data.DataSet 'create new data set
MyCommand.Fill(StatVar.DtSet1) 'fill data set with table
Form14.DataGridView1.DataSource = StatVar.DtSet1.Tables(0) 'populate gridview with data set table
MyConnection.Close()
Form14.ShowDialog()
Catch exc As Exception
MessageBox.Show("There was a problem loading this database. Please contact an administrator if the problem continues." & vbNewLine & vbNewLine & "Error: " & exc.Message)
End Try
ここでエラーが発生します:
MyCommand.Fill(StatVar.DtSet1)