我正在使用VSTS 2008 + C#+ .Net 3.5来读取Excel 2007创建的Excel文件(但保存为Excel 2003 xls格式)。这是我的代码,当执行代码adapter.Fill(cities)时,有异常 - “OldDbException找不到可安装的ISAM”。有什么想法是错的吗?
static void Main(string[] args)
{
string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\temp\data.xls;ExtendedProperties=""Excel 8.0;HDR=YES;""";
DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OleDb");
DbDataAdapter adapter = factory.CreateDataAdapter();
DbCommand selectCommand = factory.CreateCommand();
selectCommand.CommandText = "SELECT ID FROM [Sheet1$]";
DbConnection connection = factory.CreateConnection();
connection.ConnectionString = connectionString;
selectCommand.Connection = connection;
adapter.SelectCommand = selectCommand;
DataSet cities = new DataSet();
adapter.Fill(cities); // OldDbException Could not find installable ISAM
return;
}
提前谢谢,
乔治
答案 0 :(得分:2)
我复制了您的问题,用以下内容替换您的代码,它应该可以正常工作
static void Main ( string [] args )
{
string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\temp\Data.xls;Extended Properties=""Excel 8.0;HDR=YES;""";
DbProviderFactory factory = DbProviderFactories.GetFactory ( "System.Data.OleDb" );
using ( DbConnection connection = factory.CreateConnection ( ) )
{
connection.ConnectionString = connectionString;
using ( DbCommand command = connection.CreateCommand ( ) )
{
// Cities$ comes from the name of the worksheet
command.CommandText = "SELECT ID FROM [Sheet1$]";
connection.Open ( );
using ( DbDataReader dr = command.ExecuteReader ( ) )
{
DataSet cities = new DataSet ( );
cities.Load ( dr, LoadOption.OverwriteChanges, new [] { "Sheet1" } );
}
}
}
return;
}