我试图读取excel文件的内容(我必须处理数据不显示它),但行数是0.我确实在UI中显示了数据,行没有显示。有一个数字。
string src = "the path;";
OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + src +
"Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\"");
OleDbDataAdapter da = new OleDbDataAdapter("select * from [RENNES4_wk13$]", con);
DataSet ds = new DataSet();
da.Fill(ds);
DataGridView dgv = new DataGridView();
dgv.DataSource = ds.Tables[0];
int rows = dgv.Rows.Count;
int cells = dgv.Rows[0].Cells.Count;//ArgumentOutOfRange why?
我该如何解决?
答案 0 :(得分:2)
试试这个
string src = @"C:\SampleData\us-500.xls";
OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + src +
";Extended Properties=Excel 8.0;");
//con.Open();
OleDbDataAdapter da = new OleDbDataAdapter("select * from [MySheet$]", con);
DataSet ds = new DataSet();
da.Fill(ds);
BindingSource bindingSource = new BindingSource();
bindingSource.DataSource = ds.Tables[0];
var dataGridView1 = new DataGridView();
// Add data grid view as child control on form, flow Layout Panel is placed on windows form
flowLayoutPanel1.Controls.Add(dataGridView1);
dataGridView1.DataSource = bindingSource;
int rows = dataGridView1.Rows.Count;
int cells = dataGridView1.Rows[0].Cells.Count;
答案 1 :(得分:1)
试试这个:
BindingSource bindingSource = new BindingSource();
bindingSource.DataSource = resultDt;
在你的情况下:
bindingSource.DataSource = ds.Tables[0];
和
dgResult.DataSource = bindingSource;
flowLayoutPanel.Controls.Add(dgResult);
var c = dgResult.Rows.Count;
绑定源是负责将数据与控件同步的原因。您想要使用它,而不是尝试将表直接分配给控件。
参考:
Datagridview rowcount showing 0 even when there is a valid datasource