2017-02-09 10 views
0

まず、ExcelシートのデータをDataGridViewに読み込みます。ComboBoxで選択したシートをExcelから読み込む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ファイルを開き、シートごとに1つのDataTableでデータセット(またはリスト)を初期化するよりも手順を作成します。特定のシートを選択すると、DataGridView.DataSourceを変更するだけです。 – Graffito

+0

@Graffitoそれはうまくいくように聞こえます、あなたはさらに助けてくださいできますか?私はすべての私の読書方法を廃止していますか?または、私はまだそれを編集することができます...あなたはいくつかのコードを持っている場合は共有してください。 –

+0

dtexcelをリストとして定義します(変数はフォームに属し、nullに初期化されている必要があります)。 * oleDbAdapt = OleDbDataAdapter( "sheet" + sheetIndex + "1 $]"、con)*を初期化するときにエラー/例外が発生するまで、ReadExcel(リストを返します)でシートをループします。 dtexcelがnullの場合にのみ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

完全に動作します。ありがとうございました!! –

関連する問題