Rajneesh
Rajneesh

Reputation: 2291

Excel data column name changing when loaded into dataset using Microsoft.ACE.OLEDB.12.0

I have an excel sheet with 18 columns. In that 5 columns have same column name CALL_REASON. But when i load that excel sheet into a dataset using Microsoft.ACE.OLEDB.12.0. The column names in dataset are changed for the columns which had same name. it is getting loaded as CALL_REASON,CALL_REASON1,CALL_REASON2,CALL_REASON3,CALL_REASON4. They are present in excelsheet as CALL_REASON,CALL_REASON,CALL_REASON,CALL_REASON,CALL_REASON

String properties = "Excel 8.0; HDR=YES; IMEX=1;";//properties set for connection to excel
string sSourceConstr = @"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\uploads\" + fileName + ";Extended Properties=\"" + properties + "\"";

sSourceConnection = new OleDbConnection(sSourceConstr);//creating the OLEDB connection
try
{
    //select statement to select data from the first excel sheet
    string sql = string.Format("Select * FROM [{0}]", "Sheet1$");

    //commands to fill the dataset with excel data
    OleDbDataAdapter excelAdapter = new OleDbDataAdapter();
    OleDbCommand command = new OleDbCommand(sql, sSourceConnection);
    sSourceConnection.Open();
    excelAdapter.SelectCommand = command;
    excelAdapter.Fill(surveyItemDetails, "ExcelDataTable");
}

Upvotes: 2

Views: 1693

Answers (2)

Heinzi
Heinzi

Reputation: 172280

You cannot have fields with the same name in a DataTable. In fact, you cannot even have CALL_REASON and CALL_reason, see, for example, the Exceptions section in the documentation of DataColumnCollection.Add:

DuplicateNameException

The collection already has a column with the specified name. (The comparison is not case-sensitive.)

The requirement that column names must be unique makes perfect sense. What should be returned by DataRow.Field<String>("CALL_REASON"), if you were allowed to have multiple columns with that name?

Upvotes: 1

knockoutrose
knockoutrose

Reputation: 11

Access is probably changing the column names for you. Can you have fields in a database with the same names? I don't think so. When you do a select unless it's *, how are you going to select call reason when there are many fields with the same name.To experiment try using excel to export the data withcolumns to a CSV file. Then try to import the CSV file to Access. There is a wizard to step though asking if you want to keep the column names, select a field as a key or let Access create one for you. To append or create table etc...Access will tell you if it can't use the column names and create one for you.

Upvotes: 0

Related Questions