将数据从Excel Sheet加载到DataTable时遇到错误

问题描述 投票:1回答:2
using (OleDbConnection connection = new 
OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathOnly + ";Extended Properties=\"Text;HDR=" + header + ";IMEX=1;Readonly=1;Extended Properties=Excel 8.0;\""))
{
    using (OleDbCommand command = new OleDbCommand(sql, connection))
    {
        using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
        {
            dataTable = new DataTable();
            adapter.Fill(dataTable);
        }
    }
}

以上是我正在使用的代码并得到以下错误:

无法更新。数据库或对象是只读的。

有人遇到同样的问题吗?

c# excel oledb
2个回答
0
投票

您的连接字符串包含“Readonly = 1;”。尝试更改“Readonly = 0;”。并尝试删除“imex = 1”。所以你的代码应该是这样的:

    using (OleDbConnection connection = new 
OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathOnly + ";Extended Properties=\"Text;HDR=" + header + ";Readonly=0;Extended Properties=Excel 8.0;\""))
{
    using (OleDbCommand command = new OleDbCommand(sql, connection))
        {
            using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
                {
                    dataTable = new DataTable();
                    adapter.Fill(dataTable);
                 }
         }
}

0
投票

尝试使用以下语法(从扩展属性中删除Text,因为它用于导入csv文件):

using (OleDbConnection connection = new 
OleDbConnection(String.Format(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"HDR={1};IMEX=1;Readonly=1;Extended Properties=Excel 8.0;\"",pathOnly ,header )))
{
    using (OleDbCommand command = new OleDbCommand(sql, connection))
    {
        using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
        {
            dataTable = new DataTable();
            adapter.Fill(dataTable);
        }
    }
}

如果您安装了Office 2007或更高版本的提供程序,请尝试使用Microsoft.ACE.OLEDB.12.0提供程序,因为它还支持读取旧的Excel格式。

如果您尝试导入文本文件(csv),那么最好使用文本解析库,例如:

© www.soinside.com 2019 - 2024. All rights reserved.