2017-07-19 49 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

_「......但是我可以只添加帶有數據的頁面到組合框嗎?....」_ - 嗯? – 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); 
      }