如何使用OleDbConnection从Excel文件中检索数据

时间:2012-11-13 13:04:20

标签: c# .net oledb com-interop

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

任何人都可以帮我这个吗?

2 个答案:

答案 0 :(得分: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\"");

答案 1 :(得分: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;");