2

the thing is that I need to select only 2 columns from the data in Excel, so i went on using sql for retrieving the data from the Excel file. But this time i keep getting "failed to create file" error and this happens when i try to open my connection. Why is it trying to create a file ?

my code:

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);
        }
    }
}

can anyone help me with this ?

4

2 に答える 2

2

** EDITED **

Test it like this:-

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

To configure OleBConnection for read Excel file try this:

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 に答える