我只是尝试从excel中获取数据并在excel中显示它们。当我单击该按钮时,excel中的数据将列在datagridview中。
我的代码:
private void btn_load_Click(object sender, EventArgs e)
{
try
{
System.Data.OleDb.OleDbConnection MyConnection;
System.Data.DataSet DtSet;
System.Data.OleDb.OleDbDataAdapter MyCommand;
MyConnection = new System.Data.OleDb.OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='C:\Users\Dell\Desktop\kitap.xlsx';Extended Properties='Excel 12.0;HDR=Yes;IMEX=1'");
MyCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection);
MyCommand.TableMappings.Add("Table", "TestTable");
DtSet = new System.Data.DataSet();
MyCommand.Fill(DtSet);
dataGridView1.DataSource = DtSet.Tables[0];
MyConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
错误:
答案 0 :(得分:1)
试试这个
private void button1_Click(object sender, EventArgs e)
{
String name = "sheet1";
String constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
"C:\\Sample.xlsx" +
";Extended Properties='Excel 12.0 XML;HDR=YES;';";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand oconn = new OleDbCommand("Select * From [" + name + "$]", con);
con.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
DataTable data = new DataTable();
sda.Fill(data);
grid_items.DataSource = data;
}