事实是,我只需要从Excel中的数据中选择2列,所以我继续使用sql从Excel文件中检索数据。但是这一次我一直收到“无法创建文件”错误,当我尝试打开连接时会发生这种情况。为什么要尝试创建文件?

我的代码:

public void ReadExcelFile()
{
    string connectionString = string.Format(ConfigurationManager.ConnectionStrings["ExcelConnection"].ConnectionString.Replace("'", "\""), "@C:/Temp/Copy.xlsx");
    using (OleDbConnection connection = new OleDbConnection(connectionString))
    {
        try
        {
            connection.Open();
            string sqlCmd = "SELECT  * FROM [Ark1$]";
            using (OleDbCommand command = new OleDbCommand(sqlCmd, connection))
            {
                command.CommandType = System.Data.CommandType.Text;
                using (OleDbDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        Console.WriteLine(reader.ToString());
                    }
                }
            }

        }
        catch (Exception exception)
        {
            Console.WriteLine("ERROR in ReadExcelFile() method. Error Message : " + exception.Message);
        }
    }
}


谁能帮我这个 ?

最佳答案

**编辑**

像这样测试它:

string filename = "@C:\Temp\Copy.xlsx";

OleDbConnection con = new OleDbConnection(
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
filename + ";Extended Properties=\Excel 8.0;HDR=YES;IMEX=1\"");

09-25 21:16