将excel文件绑定到datagridview

时间:2010-02-05 16:22:32

标签: c# datagridview

我正在尝试将excel文件绑定到dataGridView

strConn = "Provider=Microsoft.Jet.OLEDB.4.0;"
                + "Data Source=E://Org.xls;" 
                + "Extended Properties=" + (char)34 
                + "Excel 8.0;HDR=Yes;" + (char)34;
            OleDbConnection conn = new OleDbConnection(strConn);
            textBox1.Text = "test";
            OleDbCommand command = new OleDbCommand("Select * from [Sheet1$]", conn);
            conn.Open();
            dataGridView1.DataSource = command.ExecuteReader(); 



            conn.Close();

但是网格视图没有显示任何内容。它不会给出错误

2 个答案:

答案 0 :(得分:3)

继承人如何做,只需要更改excel文件的路径和对网格的引用。

    OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c://Org.xls;Extended Properties=" + (char)34 + "Excel 8.0;HDR=Yes;" + (char)34);
    DataSet myExcelData=new DataSet();

    conn.Open();

    OleDbDataAdapter myDataAdapter = new OleDbDataAdapter("Select * from [Sheet1$]", conn);
    myDataAdapter.Fill(myExcelData);

    ultraGrid1.DataSource = myExcelData;

    conn.Close(); 

答案 1 :(得分:0)

更改该代码

ultraGrid1.DataSource = myExcelData;

到这个

dataGridView1.DataSource = myExcelData.Tables[0];