2017-02-09 85 views
0

我最初使用Excel工作表中的數據填充我的DataGridView。從Excel中使用ComboBox中的選定工作表填充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

我也有一個組合框填充表名。 enter image description here

需要發生的事情是,當用戶從組合中選擇例如「Sheet5」時,我想用所選工作表詳細信息刷新Gridview。我該怎麼做呢?我怎麼知道所有表都在Gridview中?

+0

創建一個程序,而不是打開Excel文件並初始化DataSet(或列表),每個工作表有一個DataTable。當您選擇特定工作表時,只需更改DataGridView.DataSource即可。 – Graffito

+0

@Graffito聽起來好像會起作用,你可以請進一步幫忙。我是否廢除我所有的讀取方法?或者我仍然可以編輯它...如果你有一些代碼請分享。 –

+0

只需將dtexcel定義爲列表(該變量應該屬於表單並被初始化爲空)。在ReadExcel中(這將返回列表),在表單上循環,直到初始化* oleDbAdapt = OleDbDataAdapter(「select * from [Sheet] + sheetIndex +」1 $]「,con)*時出現錯誤/異常。只有在dtexcel爲空的情況下才能調用ReadExcel,否則數據表保留並且很容易用作DataSource。在處理另一個excel文件之前,請將dtexcel重置爲null。 – Graffito

回答

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

完美的作品。謝謝!! –

相關問題