使用ComboBox

时间:2017-02-09 17:05:51

标签: c# 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文件有多个工作表。 enter image description here

我还有一个填充Sheetnames的组合框。 enter image description here

需要发生的是,当用户从组合中选择“Sheet5”时,我想用所选的工作表细节刷新Gridview。我该怎么做呢?我怎么知道所有工作表都在Gridview中?

1 个答案:

答案 0 :(得分:1)

我没有彻底测试,但似乎工作正常。假设您正在使用OLEDB ...基本上下面的代码使用DataSet来保存所有工作表。在收集工作表时,我还创建了一个简单的List<string>来保存每个工作表的名称以显示在组合框中。由于工作表和组合框是同时添加的,我们可以使用组合框选择索引来标识要显示的正确工作表(数据集中的数据表)。工作表的名称在其名称中有一个“$”符号。我在组合框中显示时删除了这个“$”。

下面的代码是一个表单,其中DataGridView用于显示数据表,ComboBox用于选择数据表,Label用于提供有关当前所选数据表的信息。希望这会有所帮助。

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";
  }
}