使用ComboBox中选定的工作表从Excel中填充DataGridview

我最初使用Excel Sheet中的数据填充我的DataGridView。

private void btnChooseAndRead_Click(object sender, EventArgs e) { Refresh(); string filePath = string.Empty; string fileExt = string.Empty; OpenFileDialog file = new OpenFileDialog();//open dialog to choose file if (file.ShowDialog() == System.Windows.Forms.DialogResult.OK)//if there is a file choosen by the user { filePath = file.FileName;//get the path of the file fileExt = Path.GetExtension(filePath);//get the file extension if (fileExt.CompareTo(".xls") == 0 || fileExt.CompareTo(".xlsx") == 0) { try { cmbSheetName.Text = ""; cmbSheetName.Items.Clear(); string[] names = GetExcelSheetNames(file.FileName); //Populate Combobox with Sheet names foreach (string name in names) { cmbSheetName.Items.Add(name); } DataTable dtExcel = new DataTable(); dtExcel = ReadExcel(filePath, fileExt); //read excel file cmbSheetName.Visible = true; lblFileName.Text = file.SafeFileName.ToString(); BindingSource theBindingSource = new BindingSource(); dgvViewData.Visible = true; dgvViewData.DataSource = dtExcel; //dgvViewData.ColumnDisplayIndexChanged = true; //cmbSheetName_SelectedIndexChanged(sender, e); } catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); } } else { MessageBox.Show("Please choose .xls or .xlsx file only.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Error);//custom messageBox to show error } } } public DataTable ReadExcel(string fileName, string fileExt) { string conn = string.Empty; DataTable dtexcel = new DataTable(); if (fileExt.CompareTo(".xls") == 0)//compare the extension of the file conn = @"provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + ";Extended Properties='Excel 8.0;HRD=Yes;IMEX=1';";//for below excel 2007 else conn = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1';";//for above excel 2007 using (OleDbConnection con = new OleDbConnection(conn)) { try { OleDbDataAdapter oleAdpt = new OleDbDataAdapter("select * from [Sheet1$]", con);//here we read data from sheet1 oleAdpt.Fill(dtexcel);//fill excel data into dataTable } catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); } } return dtexcel; } 

这工作得很好,现在我正在阅读的Excel文件有不止一张纸。 在这里输入图像说明

我也有一个combobox填充表名。 在这里输入图像说明

需要发生的事情是,当用户从组合中select例如“Sheet5”时,我想用选定的工作表详细信息刷新Gridview。 我该怎么做呢? 我怎么知道所有表都在GridView?

我没有完全testing,但它似乎工作正常。 假设你正在使用OLEDB …基本上下面的代码使用DataSet来保存所有的工作表。 在收集工作表时,我还创build了一个简单的List<string>来保存每个工作表的名称以显示在combobox中。 由于工作表和combobox是同时添加的,我们可以使用comboboxselect索引来标识正确的工作表(数据集中的数据表)以显示。 工作表的名称在名称中有一个“$”符号。 当显示到combobox时,我删除了这个“$”。

下面的代码是一个DataGridView显示数据表的窗体,一个ComboBox来select一个数据表和一个Label来给出有关当前select的数据表的信息。 希望这可以帮助。

 public partial class Form1 : Form { private string Excel07ConString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\YourFilePath\YourFile.xls;Extended Properties='Excel 12.0 Xml;IMEX=1;HDR=NO;TypeGuessRows=0;ImportMixedTypes=Text'"; string sheetName; DataSet ds; List<string> comboBoxData = new List<string>(); public Form1() { InitializeComponent(); SetDataTablesFromExcel(); dataGridView1.DataSource = ds.Tables[0]; comboBox1.DataSource = comboBoxData; label1.Text = "TableName: " + ds.Tables[0].TableName + " has " + ds.Tables[0].Rows.Count + " rows"; } private void SetDataTablesFromExcel() { ds = new DataSet(); using (OleDbConnection con = new OleDbConnection(Excel07ConString)) { using (OleDbCommand cmd = new OleDbCommand()) { using (OleDbDataAdapter oda = new OleDbDataAdapter()) { cmd.Connection = con; con.Open(); DataTable dtExcelSchema = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null); for (int i = 0; i < dtExcelSchema.Rows.Count; i++) { sheetName = dtExcelSchema.Rows[i]["TABLE_NAME"].ToString(); DataTable dt = new DataTable(); cmd.Connection = con; cmd.CommandText = "SELECT * FROM [" + sheetName + "]"; oda.SelectCommand = cmd; oda.Fill(dt); dt.TableName = sheetName; comboBoxData.Add(sheetName.Replace("$", "")); ds.Tables.Add(dt); } } } } } private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { int index = comboBox1.SelectedIndex; dataGridView1.DataSource = ds.Tables[index]; label1.Text = "TableName: " + ds.Tables[index].TableName + " has " + ds.Tables[index].Rows.Count + " rows"; } }