2017-07-19 2 views
-4

Excelファイルを開くプログラムを作った。CのExcelスプレッドシートを読んで

データページと空白ページがあります。 データが存在するページのみをコンボボックスに追加できますか? ButtonEventを使用してデータを含むページのみを表示できますか?

 string filePath = openFileDialog1.FileName;//파일 경로 가져오기 
     string filename = openFileDialog1.SafeFileName;//파일 이름만 가져오기 
     string fileExtension = Path.GetExtension(filePath); 

     //string connectionString = string.Empty; 
     string sheetName = string.Empty; 

    using (OleDbConnection con = new OleDbConnection(ConnectStr())) 
     { 
      using (OleDbCommand cmd = new OleDbCommand()) 
      { 
       using (OleDbDataAdapter oda = new OleDbDataAdapter()) 
       { 
        DataTable dt = new DataTable(); 

        cmd.CommandText = "SELECT * From [" + sheetName + "]"; 
        cmd.Connection = con; 
        con.Open(); 
        oda.SelectCommand = cmd; 
        oda.Fill(dt); 
        con.Close(); 

        dataGridView1.DataSource = dt; 

       } 
      } 
     } 

public string ConnectStr() 
    { 
     string filePath = openFileDialog1.FileName; 
     string filename = openFileDialog1.SafeFileName;//파일 이름만 가져오기 
     string fileExtension = Path.GetExtension(filePath); 

     string connectionString = string.Empty; 
     string sheetName = string.Empty; 

     switch (fileExtension) 
     { 
      case ".xls": //Excel 97-03버전 

       connectionString = string.Format(Excel03ConString, filePath); 
       break; 
      case ".xlsx": //Excel 07이상 버전 
       connectionString = string.Format(Excel16ConString, filePath); 
       break; 
     } 
     return connectionString; 
    } 
+1

_ "....でも、データ付きのページだけをコンボボックスに追加することはできますか?" _ _huh? – MickyD

+2

_ "...ボタンイベントを通じてデータを持つページだけが見えますか?" _ - 意味が分かりません – MickyD

+0

Excelファイルには64ページあります。データが存在するページと空白のページ。データのみのページがコンボボックスに追加されます。 ButtonEventを使用して、データを含むページのみを表示できますか? –

答えて

0

これは実際にはわかりません。しかし、もし私が間違っていれば、スプレッドシートの特定のシートのみを修正してください。

特定のシートから照会できるSQLがあります。

try 
      { 
       this.txtImportFilePath.Text = opd.FileName; 
       OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;data source=" + this.txtImportFilePath.Text + ";Extended Properties=Excel 8.0;"); 

       StringBuilder stbQuery = new StringBuilder(); 
       stbQuery.Append("Select * From [Sheet1$]"); 
       OleDbDataAdapter adp = new OleDbDataAdapter(stbQuery.ToString(), con); 

       DataSet dsXLS = new DataSet(); 
       adp.Fill(dsXLS); 

       DataView dvEmp = new DataView(dsXLS.Tables[0]); 

       trnxlistDataview.DataSource = dvEmp; 
      } 
      catch (Exception ex) 
      { 
       MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message); 
      } 
関連する問題