I am working on a tool that basically allow users select an excel file from their computer, preview it in a datagrid before submitting to the database. Currently this is what the code that opens the file looks like private void btn_browse_file_Click(object sender, EventArgs e) { OpenFileDialog openFileDialog1 = new OpenFileDialog(); openFileDialog1.CheckFileExists = true; openFileDialog1.AddExtension = true; openFileDialog1.Multiselect = false; openFileDialog1.Filter = "Excel files (*.xls) | *.xlsx"; openFileDialog1.Title = "Select a spreadsheet file"; if (openFileDialog1.ShowDialog() == DialogResult.OK) { openFileDialog1.OpenFile(); // MessageBox.Show(openFileDialog1.FileName.ToString()); label_display_file_name.Text = openFileDialog1.FileName.ToString(); } }and this is the code that is meant to display the excel file in the datagridviewprivate void btn_preview_Click(object sender, EventArgs e){ OleDbConnection ConnectToExcel = new OleDbConnection(); DataSet excelds = new DataSet(); OleDbDataAdapter excelda = new OleDbDataAdapter(); OleDbCommand excelcmd = new OleDbCommand(); ConnectToExcel = new OleDbConnection (String.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0;HDR=YES;IMEX=1;""", openFileDialog1.FileName.ToString())); excelcmd = new OleDbCommand (String.Format("SELECT * FROM [{0}$]", ConnectToExcel, openFileDialog1.FileName)); excelda = new OleDbDataAdapter(excelcmd); excelda.Fill(excelds); dataGridView1.DataSource = excelds.Tables[0];}For some reasons I don't yet know, the code to display the excel file on the datagrid gives me the following error "Fill:SelectCommand.Connection property has not been initialized". Any help or ideas on how to get this work will be much appreciated. 解决方案 这篇关于如何从excel电子表格中选择数据并绑定到datagrid的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-28 19:42