有没有办法读取 excel 中每一行的某些列?

Is there a way to read certain columns of every row in excel?

首先,我是 C# 的新手。 我想 select 我的 excel sheet 的每一行并将其放入文本文档中。问题是,我只需要某些列(70 多个列中的 21 个)。

这是我的代码:

例如:

Excel:
 |1  2  3  4  5
1|x  y  c  v  b
2|x  y  c  v  b
3|x  y  c  v  b

我需要第 1 到 3 行的每一行,但只需要第 2、3、5 列的数据

在我的文本文档中,我希望它喜欢:
y c b
y c b
y c b
但是 atm 看起来像:
y
y
y
c
c
c
b
b
b

int[] spalten = new int[] { 5, 22, 24, 27, 29, 32, 34, 37, 39, 43, 45, 48, 50, 54, 56, 59, 61, 65, 67, 71, 73 };
for (int x = 0; x <= 20; x++)
{
  //loop all columns 
  for (int j = 4; j <= 74; j++)
  {
    //loop all rows
    for (int i = 5; worksheet.Cells[i, 5].Value != null; i++)
    {
      //add the cell data to the List
      if (j == spalten[x])
     {
         if (worksheet.Cells[i, j].Value == null)
         {
           Console.WriteLine("leer");
           string Inhalt = "leer" + "\t";
           string[] lines = { Inhalt };

           File.AppendAllLines(Path.Combine(docPath, "Daten2.txt"), lines);
        }
      else
      {
       excelData.Add(worksheet.Cells[i, j].Value.ToString());
       Console.WriteLine(worksheet.Cells[i, j].Value);
       string Inhalt = worksheet.Cells[i, j].Value.ToString()+"\t";
       string[] lines = { Inhalt };
       File.AppendAllLines(Path.Combine(docPath, "Daten2.txt"), lines);                                      
      }          
     }
   }

}


 }

更改循环顺序:首先循环行,然后循环当前行的列。在内部循环中,将列值连接成一个字符串。

出于性能原因,请尝试在循环内做尽可能少的工作(例如,不要使用相同的索引访问 worksheet.Cells[] 两次)。使用 StringBuilder to concatenate strings. You can use foreach 仅循环遍历配置的列。

var configuredColumns = new int[] { 5, 22, 24, 27, 29, 32, 34, 37, 39, 43, 45, 48, 50, 54, 56, 59, 61, 65, 67, 71, 73 };   

// loop over all data rows (ignore first 5 rows which are headers)
// stop looping if the current row has no data in column 5
var allRowTexts = new List<string>();
for (int row = 5; worksheet.Cells[row, 5].Value != null; row++) {

    // loop over the configured columns
    var rowText = new StringBuilder();
    foreach (var col in configuredColumns) {

        var cell = worksheet.Cells[row, col];
        if (cell.Value == null) {
            rowText.Append("leer" + "\t");
        }
        else {
            rowText.Append(cell.Value.ToString() + "\t");                
        } 
    }

    // rowText now contains all column values for the current row
    allRowTexts.Add(rowText.ToString());
}

// write all rows into file
File.AppendAllLines(Path.Combine(docPath, "Daten2.txt"), allRowTexts); 

C# Fiddle using dummy WorkSheet and Console output