2013-07-16 85 views
0

我正在將Excel文件導入到DataTable中,然後從每個後續DataRow獲取所需的信息,然後將其插入到列表中。 我有一個方法,當我需要將Excel(.xlsx或.xls)文件導入到DataTable中時,我會調用它,並且在我的程序中使用它6或7個其他位置,所以我很確定沒有有任何錯誤。將Excel文件讀入DataTable將返回DataRows中的空字段

我的問題是,當我訪問DataRow時,在這個特定的DataTable上,前幾個字段包含值,但其他一切都只是空值。 如果我在本地窗口中看到它,我可以看到的DataRow看起來是這樣的:

[0] {"Some string value"} 
[1] {} 
[2] {} 
[3] {} 

當它應該是這樣的:

[0] {"Some string value"} 
[1] {"Another string value"} 
[2] {"Foo"} 
[3] {"Bar"} 

這裏是處理進口的方法:

public List<DataTable> ImportExcel(string FileName) 
     { 
      List<DataTable> _dataTables = new List<DataTable>(); 
      string _ConnectionString = string.Empty; 
      string _Extension = Path.GetExtension(FileName); 
      //Checking for the extentions, if XLS connect using Jet OleDB 
      if (_Extension.Equals(".xls", StringComparison.CurrentCultureIgnoreCase)) 
      { 
       _ConnectionString = 
        "Provider=Microsoft.Jet.OLEDB.4.0; Data Source={0};Extended Properties=Excel 8.0"; 
      } 
      //Use ACE OleDb 
      else if (_Extension.Equals(".xlsx", StringComparison.CurrentCultureIgnoreCase)) 
      { 
       _ConnectionString = 
        "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 8.0"; 
      } 

      DataTable dataTable = null; 
      var count = 0; 
      using (OleDbConnection oleDbConnection = 
       new OleDbConnection(string.Format(_ConnectionString, FileName))) 
      { 
       oleDbConnection.Open(); 
       //Getting the meta data information. 
       //This DataTable will return the details of Sheets in the Excel File. 
       DataTable dbSchema = oleDbConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables_Info, null); 
       foreach (DataRow item in dbSchema.Rows) 
       { 
        //reading data from excel to Data Table 
        using (OleDbCommand oleDbCommand = new OleDbCommand()) 
        { 
         oleDbCommand.Connection = oleDbConnection; 
         oleDbCommand.CommandText = string.Format("SELECT * FROM [{0}]", 
          item["TABLE_NAME"].ToString()); 

         using (OleDbDataAdapter oleDbDataAdapter = new OleDbDataAdapter()) 
         { 
           if (count < 3) 
           { 
            oleDbDataAdapter.SelectCommand = oleDbCommand; 
            dataTable = new DataTable(item["TABLE_NAME"].ToString()); 
            oleDbDataAdapter.Fill(dataTable); 
            _dataTables.Add(dataTable); 
            count++; 
           } 
         } 
        } 
       } 
      } 
      return _dataTables; 
     } 

有什麼想法?

回答

1

原來故障是與Excel文檔。 顯然Excel文檔有一個名爲Shared Strings的隱藏表。 這是因爲這張表我找不到我想要的值。