2013-03-11 87 views
0

我想讀取excel中的excel文件,但由於某種原因某個時候,第一列丟失,第一行從數據中丟失。在Excel中缺失第一列和第一行C#

當我在Excel中打開文件並保存它沒有任何更改時,文件被正確讀取。

關於這可能發生的任何想法?

下面是我用來讀取文件的代碼:

string xlConn = "Provider=Microsoft.Jet.OLEDB.4.0;" 
      + "Data Source=" 
      + txt_InputFile.Text 
      + ";Extended Properties=Excel 8.0;"; 

using (OleDbConnection dbConnection = new OleDbConnection(xlConn)) 
{ 
    dbConnection.Open(); 

    // Get the name of the first worksheet: 
    DataTable dbSchema = dbConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null); 
    if (dbSchema == null || dbSchema.Rows.Count < 1) 
    { 
     //"Error: Could not determine the name of the first worksheet." 
     throw new Exception(Program.lm_GetMethodLanguage(this.GetType().Name, "wp_InputFile_CloseFromNext", 5)); 
    } 
    string firstSheetName = dbSchema.Rows[0]["TABLE_NAME"].ToString(); 

    using (
     OleDbDataAdapter dbCommand = new OleDbDataAdapter("SELECT * FROM [" + firstSheetName + "]", 
                  dbConnection)) 
    { 
     using (DataSet myDataSet = new DataSet()) 
     { 
      dbCommand.Fill(myDataSet); 

      inputData = myDataSet.Tables[0]; 
     } 
    } 
} 
+2

嘗試在連接字符串中設置'HDR = No',也許? – 2013-03-11 14:52:48

+0

我試着給連接字符串添加「HRD = No」,我得到以下異常:「無法找到可安裝的ISAM。」 – 2013-03-11 14:56:15

+0

我剛剛通過添加引號解決了這個錯誤,但缺少第一列和第一行的問題仍然存在 – 2013-03-11 15:15:08

回答

-1

使用this.This將檢索Excel工作表的所有工作表。

private String[] GetExcelSheetNames(string excelFile) 
    { 
     try 
     { 
      excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + ""yoursourcepath"+ ";Extended Properties=Excel 12.0;Persist Security Info=False"; 
      excelConnection = new OleDbConnection(excelConnectionString); 
      excelConnection.Open(); 
      dt = excelConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null); 

      if (dt == null) 
      { 
       return null; 
      } 

      excelSheets = new String[dt.Rows.Count]; 
      int i = 0; 


      foreach (DataRow row in dt.Rows) 
      { 
       excelSheets[i] = row["TABLE_NAME"].ToString(); 
       i++; 
      } 

      return excelSheets; 
     } 
     catch (Exception ex) 
     { 
      return null; 
     } 
     finally 
     { 
      if (excelConnection != null) 
      { 
       excelConnection.Close(); 
       excelConnection.Dispose(); 
      } 
      if (dt != null) 
      { 
       dt.Dispose(); 
      } 
     } 
    } 
+0

這是否適用於excel 2003? – 2013-03-11 15:14:36

+0

@AhmadHajou不,這隻適用於2007年及以後。此外,這隻會檢索工作表_names_,而不是工作表_data_。 – 2013-03-11 15:36:09