2013-01-08 60 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查询来读取文件中的数据。