2013-03-11 86 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