2

问题是我只需要从 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);
        }
    }
}

谁能帮我这个 ?

4

2 回答 2

2

** 已编辑 **

像这样测试它: -

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\"");
于 2012-11-13T13:16:57.560 回答
0

要为读取 Excel 文件配置 OleBConnection,请尝试以下操作:

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

OleDbConnection connection =new OleDbConnection(
                         "provider=Microsoft.Jet.OLEDB.4.0;Data Source='"+filename+"';"+
                         "Extended Properties=Excel 8.0;");
于 2014-11-28T08:54:10.913 回答