未识别的数据库格式。

3

我想问一下,为什么我在尝试连接Excel 2000/3和2010时会出现这个异常?

using System;
using System.Collections.Generic;
using System.Text;
using System.Data.OleDb;

namespace md1_connect
{
    class Program
    {

        static void Main (string[] args)
        { 
            string ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\"Book1.xls\"";            
            OleDbConnection MyConn = new OleDbConnection(ConnectionString);
            OleDbCommand cmd = new OleDbCommand("SELECT * FROM[Sheet2$]", MyConn);
            MyConn.Open();
            OleDbDataReader dataReader = cmd.ExecuteReader();

            while (dataReader.Read())
            {
                Console.WriteLine(dataReader.GetDouble(0));
            }
            MyConn.Close();
        }
    }
}

1
尝试编译针对32位平台的代码。 - Crono
1
@Tarec 我猜是“无法识别的数据库格式”。从标题来看。 - itsme86
您可以使用Udl文件技巧来简化创建连接字符串的过程。 - Steve B
@Crono1981 我已经使用了“优先选择32位”,所以这不会是一个问题。 - Imants Volkovs
2个回答

3
您需要告诉提供者您正在使用Excel 97-2003(xls而不是xlsx),方法是在后面添加以下内容:
Extended Properties="Excel 8.0"

例如:

string ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\"Book1.xls\";Extended Properties=\"Excel 8.0\"";

我尝试了那个,但它抛出了错误,说连接字符串不正确,当我加入那行时。 - Imants Volkovs

1
我不知道异常是什么,但我可能知道你在说什么。你可能正在编译为x64位,请强制将其作为32位(x86)运行。我相信该设置可以在您的项目属性下的构建选项中设置。

我有32位操作系统,所以它不能在32位编译吗? - Imants Volkovs

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接