处理Excel文件中的额外列 – C#

在我的应用程序中,我需要读取一个Excel文件,并以表格格式显示标题(标题)。 这工作很好迄今。 但对于一些Excel文件显示(excel文件有20列)一些额外的列(列21,列22等)。 不知道为什么它显示这些额外的列时,我检查了Excel文件,它只有20列21或22列是完全空的。 不知道为什么我的显示这些额外的列。 当我试图debugging代码“myReader.FieldCount”显示22列。 我试图以编程方式删除那些空的列。 但它提出了与行数据有关的其他问题。 对于某些行,它只显示18列或15列,因为某些列缺less数据。 有没有更好的方法来处理excel。 这是我的代码

@@@@@@@@@@@@@

if (sourceFile.ToUpper().IndexOf(".XLSX") >= 0) // excel 2007 or later file strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + sourceFile + ";Extended Properties=\"Excel 12.0;HDR=No;\""; else // previous excel versions strConn = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + sourceFile + ";Extended Properties=\"Excel 8.0;HDR=No;\""; OleDbConnection conn = null; StreamWriter wrtr = null; OleDbCommand cmd = null; OleDbDataReader myReader = null; try { conn = new OleDbConnection(strConn); conn.Open(); cmd = new OleDbCommand("SELECT * FROM [" + worksheetName + "]", conn); cmd.CommandType = CommandType.Text; myReader = cmd.ExecuteReader(); wrtr = new StreamWriter(targetFile); while (myReader.Read()) { List<string> builder = new List<string>(); for (int y = 0; y < myReader.FieldCount; y++) { if(!string.IsNullOrEmpty(myReader[y].ToString())) builder.Add("\"" + myReader[y].ToString() + "\""); } wrtr.WriteLine(string.Join(",", builder)); } 

而不是SELECT *列出你想要select的列:

 cmd = new OleDbCommand("SELECT col1, col2, col3 FROM [" + worksheetName + "]", conn); 

最好的解决scheme是通过正则expression式来判断和过滤列名一旦列为空,C#会自动生成列名,如'F21''F22'(21表示空列是第21列)

 DataTable x = ... // x is DataTable Name int index = ... // index is the column sequence no. string col = x.Columns[index].Columnname.ToString().Trim(); if (!System.Text.RegularExpressions.Regex.IsMatch(col, "^[AZ]{1}[0-9]*")) // do something