如何在 C# 中处理类似于 excel sheet 的结构良好的文本

How to process a well structured text similar to excel sheet in c#

我使用 ado.net 代码从文本文件中获取数据并将其保存到数据库中。文本文件包含以下形式的数据:列,行格式,但我不知道出了什么问题,我缺少文本文件中的某些数据。使用的代码如下所示

 string filename = @"D:\EMS_DATA\firstfile.txt";
 string[] rows = null;
 string[] cols = null;
 int counter = 0;
 using (StreamReader reader = new StreamReader(filename))
 {
     string[] lines = File.ReadAllLines(filename).Where(arg => !string.IsNullOrWhiteSpace(arg)).ToArray();
     cols = lines[0].Trim().Split(new[] { '\t' }, StringSplitOptions.RemoveEmptyEntries);

     foreach (string line in lines.Skip(1))
     {
         rows = line.Trim().Split(new[] { '\t' }, StringSplitOptions.RemoveEmptyEntries);

         for (int i = counter; i <cols.Length; i++)
         {
             for (int j = counter; j <rows.Length; j++)
             {
                 Console.WriteLine("values are {0}{1}", cols[counter], rows[counter]);
                 ++counter;
                 break;
             }
         }
     }
 }

Tex文件格式如下

firstname  lastname  salary  age
sasi   kiran    88000   32
ravi   kiran    92000   23
jafer  sharif   34000   45
kiran  bedi     45000   34

如果您不打算使用它,请先删除 StreamReader。其次,您不需要两个嵌套的 for 循环。然后在代码中实际使用 for 循环变量。还要防止条目少于 header 的行。最后你可以添加一个变量来跟踪当前行。

string filename = @"D:\EMS_DATA\firstfile.txt";
string[] lines = File.ReadAllLines(filename)
    .Where(arg => !string.IsNullOrWhiteSpace(arg)).ToArray();
string[] cols = lines[0].Trim()
    .Split(new[] {'\t'}, StringSplitOptions.RemoveEmptyEntries);

int line = 1;
foreach (string line in lines.Skip(1))
{
    string[] cells = line.Trim()
        .Split(new[] {'\t'}, StringSplitOptions.RemoveEmptyEntries);
    for (int counter = 0; counter < cols.Length; counter++)
    {
        string cellValue = "N/A";
        if(counter < cells.Length)
            cellValue = cells[counter];
        Console.WriteLine(
            "values at row {0} column {1} are {2} : {3}", 
            line, 
            counter, 
            cols[counter], 
            cellValue);
    }

    line++;
}