Import Excel to Datagridview

后端 未结 4 1471
粉色の甜心
粉色の甜心 2020-12-03 03:54

I\'m using this code to open an excel file and save it in a DataGridView:

string name = \"Items\";
string constr = \"Provider = Microsoft.Jet.OLEDB.4.0; Data         


        
4条回答
  •  醉酒成梦
    2020-12-03 04:52

    try this following snippet, its working fine.

    private void button1_Click(object sender, EventArgs e)
    {
         try
         {
                 OpenFileDialog openfile1 = new OpenFileDialog();
                 if (openfile1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                 {
                       this.textBox1.Text = openfile1.FileName;
                 }
                 {
                       string pathconn = "Provider = Microsoft.jet.OLEDB.4.0; Data source=" + textBox1.Text + ";Extended Properties=\"Excel 8.0;HDR= yes;\";";
                       OleDbConnection conn = new OleDbConnection(pathconn);
                       OleDbDataAdapter MyDataAdapter = new OleDbDataAdapter("Select * from [" + textBox2.Text + "$]", conn);
                       DataTable dt = new DataTable();
                       MyDataAdapter.Fill(dt);
                       dataGridView1.DataSource = dt;
                 }
          }
          catch { }
    }
    

提交回复
热议问题