2013-01-08 59 views
3

Possible Duplicate:
Excel 「External table is not in the expected format.」麻煩與「外部表不是預期的格式」例外

我正在做的是讓所有的表名,並將其插入到一個列表。這是我的代碼:

public List<string> GetEditExcelSheets(string fileName, out OleDbException Error) 
{ 
    List<string> Result = new List<string>(); 
    Error = null; 
    if (!string.IsNullOrEmpty(fileName) && File.Exists(fileName)) 
    { 
     string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=\"Excel 12.0 XML;HDR=YES;IMEX=1\""; 

     if (!string.IsNullOrEmpty(connectionString)) 
     { 
      using (OleDbConnection connection = new OleDbConnection(connectionString)) 
      { 
       try 
       { 
        connection.Open(); 
        DataTable tables = connection.GetSchema("Tables"); 
        foreach (DataRow row in tables.Rows) 
        { 
         string TableName = Convert.ToString(row["TABLE_NAME"]); 
         Result.Add(TableName); 
        } 
       } 

       catch (OleDbException ex) 
       { 
        Error = ex; 
       } 
       finally 
       { 
        if (connection.State == System.Data.ConnectionState.Open) 
        { 
         connection.Close(); 
        } 
       } 
      } 
     } 
    } 
    return Result; 
} 

我得到這個錯誤:達到該行代碼時

"'External table is not in the expected format'"

connection.Open(); 

我曾嘗試編輯連接字符串幾次在谷歌搜索解決方案後。但沒有其他連接字符串可以幫助我,並且此連接字符串應該可以工作我似乎可以弄清楚我做錯了什麼。

+0

您是否提供完全限定的文件名? – prthrokz

+0

您是否確定了您正在嘗試打開的現有Excel表單是您編碼爲字符串的正確版本? – RhysW

+0

@詹姆斯(和其他人):你有沒有讀過建議的重複?至少接受的答案沒有幫助,因爲他已經使用了連接字符串。 –

回答

1

我找到了解決方案。由於我使用的是開放式XML SDK,xlsx文件是使用xlsx擴展名保存的,但該文件不是Excel文件。這是一個以xlsx擴展名保存的開放xml文件,因此Excel可以打開它。這意味着我不能使用sql查詢來讀取文件中的數據。