使用GetOleDbSchemaTable读取Excel列名时发出问题

时间:2010-05-05 12:56:35

标签: .net excel c#-3.0

经过一些谷歌搜索后,我发现了如何阅读excel列名How To Retrieve Schema Information by Using GetOleDbSchemaTable and Visual Basic .NET 。虽然样本是在VB.Net中,但我使用的是C#.net。 我的代码是:

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

                }
}

但是我发现列字段是空白的,从而得到异常

位置0没有行。

excel文件看起来像

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

我确保通过了正确的文件&表名。

1 个答案:

答案 0 :(得分:0)

位置0没有行。

尝试

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

抱歉,我的语法可能略有不同 - 我更像是一个VB.net人。

相关问题