I am trying to read Excel data and its columns in C# code but unfortunately it is unable to read all header rows properly. What can be the problem ?
The Excel file look like this:
The code is only failing for get excel headers but working very well for reading other values. In the connection string you will notice i have included "HDR=NO" for reading excel header too.
The code is:
string path = Server.MapPath("~/Content/Upload/sale.xlsx");
OleDbCommand cmd;
string excelConnectionString = @"Provider='Microsoft.ACE.OLEDB.12.0';Data Source='" + path + "';Extended Properties='Excel 12.0;HDR=NO'";
OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
cmd = new OleDbCommand("Select * from [Sheet1$]", excelConnection);
StringBuilder sb = new StringBuilder();
sb.Append("<table>");
excelConnection.Open();
OleDbDataReader dReader;
dReader = cmd.ExecuteReader();
do
{
int count = dReader.FieldCount;
while (dReader.Read())
{
sb.Append("<tr>");
for (int i = 0; i < count; i++)
{
sb.Append("<td>" + dReader.GetValue(i) + "</td>");
}
sb.Append("</tr>");
}
} while (dReader.NextResult());
sb.Append("</table>");
In the below picture i have marked not all header columns name are coming in the string builder object (sb).
Please help !
UPDATE - I solved by including XML and IMEX=1 in my connection string so the corrected coonection string code is:
string excelConnectionString = @"Provider='Microsoft.ACE.OLEDB.12.0';Data Source='" + path + "';Extended Properties='Excel 12.0 Xml;HDR=NO;IMEX=1'";