0

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: enter image description here

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).

enter image description here

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'";
yogihosting
  • 5,494
  • 8
  • 47
  • 80
  • no just plain text in header. – yogihosting May 11 '17 at 18:25
  • 1
    @MethodMan thank you for providing me the solution. I change the connection string to include - "Xml;IMEX=1" and my problem is solved. So my new connection string code that worked is - string excelConnectionString = @"Provider='Microsoft.ACE.OLEDB.12.0';Data Source='" + path + "';Extended Properties='Excel 12.0 Xml;HDR=NO;IMEX=1'"; – yogihosting May 11 '17 at 18:32
  • awesome.. glad I could quickly point you to a link with the correct Connection String – MethodMan May 11 '17 at 18:34

0 Answers0