【发布时间】:2013-01-08 10:09:48
【问题描述】:
我正在做的是获取所有表名并将它们插入到列表中。这是我的代码:
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;
}
我收到此错误:
"'外部表不是预期的格式'"
到达此代码行时:
connection.Open();
在谷歌上搜索解决方案后,我曾尝试编辑连接字符串几次。但是没有其他连接字符串可以帮助我,并且这个连接字符串应该可以工作。我似乎可以弄清楚我做错了什么。
【问题讨论】:
-
您是否提供了完全限定的文件名?
-
您是否确定您尝试打开的现有 Excel 工作表是您在字符串中编码的正确版本?
-
@James(和其他人):你读过建议的副本吗?至少接受的答案没有帮助,因为他已经使用了那个连接字符串。
-
@Lahib: 你要打开哪个版本的 excel,xls 还是 xlsx?
-
我刚刚检查了它正在使用的文件是否包含一张工作表,并且它正在使用正确的 excel 文件。并且没有该文件的副本。这是完整连接字符串的样子: Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\users\lmy\documents\visual studio 2012\Projects\CustomerImportV2\CustomerImportV2\Upload\20130108111646excel.xlsx ;扩展属性="Excel 12.0 XML;HDR=YES;IMEX=1"