在我的应用程序中,我需要读取excel文件并以表格格式显示标题(标题)。 迄今为止,这工作正常。但对于一些Excel文件,它显示(excel文件有20列)一些额外的列(列21,列22等)。不知道为什么它显示这些额外的列 当我检查了Excel文件,它只有20列和21或22列是完全空的。 不知道为什么我的显示这些额外的列。 当我试图调试代码“myReader.FieldCount”显示22列。 我试图以编程方式删除那些空的列。 但它提出了与行数据有关的其他问题。对于某些行,其仅显示18列或15列,因为 缺少某些列的数据。 有没有更好的方法来处理excel。 这里是我的代码处理Excel文件中的额外列 - C#
@@@@@@@@@@@@@
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));
}
一些意见。如果您只想获取列标题,则不需要使用DataReader遍历表中的所有行;只要检查第一行,假设这是他们所在的位置。你提到你忽略了连续的空白字段,但是你为什么只看到X个作为输出......这是什么?请记住,空格也被视为字符,所以如果一个单元格显示为空,它可能不是。使用string.Trim()或String.IsNullOrWhiteSpace(.NET 4.0>)来确保你没有包含“空白”空格。 –