After some google searching I found out how to read excel column names How To Retrieve Schema Information by Using GetOleDbSchemaTable and Visual Basic .NET . Though the sample is in VB.Net, I am using C#.net. My code is :
经过一些谷歌搜索后,我发现如何阅读excel列名称如何使用GetOleDbSchemaTable和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();
}
}
But I am finding that the column field is blank and henceforth getting the exception
但我发现列字段是空白的,从而得到例外
There is no row at position 0.
位置0没有行。
The excel file looks as
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
and I have ensured that I am passing the right file & sheet name.
我确保我传递了正确的文件和工作表名称。
1 个解决方案
#1
0
There is no row at position 0.
位置0没有行。
Try
if (dtColumnNames != null) {
if(dtColumnNames.Rows.Count > 0){
strColumnName = ColumnNames.Rows[0]["COLUMN_NAME"].ToString
}
}
Sorry I may have the syntax slightly out - I'm more of a VB.net guy.
对不起,我的语法可能略有不同 - 我更像是一个VB.net人。
#1
0
There is no row at position 0.
位置0没有行。
Try
if (dtColumnNames != null) {
if(dtColumnNames.Rows.Count > 0){
strColumnName = ColumnNames.Rows[0]["COLUMN_NAME"].ToString
}
}
Sorry I may have the syntax slightly out - I'm more of a VB.net guy.
对不起,我的语法可能略有不同 - 我更像是一个VB.net人。