Problem reading excel column names using GetOleDbSchemaTable

After some googling, I found out how to read excel column names. How to get schema information using GetOleDbSchemaTable and Visual Basic.NET . Although the sample is in VB.Net, I use C # .net. My code is:

public DataSet ReadXslToDataset(string fileName,string sheetName)
            {
                ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+fileName+";Extended Properties='Excel 8.0;HDR=YES;IMEX=1'";
                using (objConn = new OleDbConnection(ConnectionString))
                {
                        objConn.Open();

                        String[] restrection = { null, null, sheetName, null };
                        dtColumnNames = objConn.GetOleDbSchemaTable  (OleDbSchemaGuid.Columns, restrection);
                        string strColumnName = string.Empty;
                        if (dtColumnNames != null)

                          strColumnName = dtColumnNames.Rows[0]["COLUMN_NAME"].ToString();

                }
}

But I find that the column field is empty and henceforth gets an exception

There is no line at position 0.

The excel file looks like

S.No    Issue
1      log4net message pattern not displayed properly in the log file
2      Reading blank rows from Excel while populating into dataset

and I made sure to pass the correct file and sheet name.

+3
source share
1 answer

There is no line at position 0.

Try

if (dtColumnNames != null) {
   if(dtColumnNames.Rows.Count > 0){
      strColumnName = ColumnNames.Rows[0]["COLUMN_NAME"].ToString
    }
  }

Sorry, I might have a little syntax - I'm more of a person from VB.net.

0
source

Source: https://habr.com/ru/post/1744153/


All Articles