0

如何使用 C# 和 NPOI 库对 Excel 电子表格中的数据进行排序?

excel电子表格非常简单。有两列带有标题,“姓名”(A 列)和“生日”(B 列)。数据绝不是排序的。

我的目标是按名称的字母顺序对列表进行排序。当然,每个名称仍应与正确的生日相匹配。

我该怎么做呢?

4

1 回答 1

3

这是一个工作示例。您需要根据需要为您的文件修改它:

  // start by loading the workbook
  HSSFWorkbook workbook;
  using (var stream = new FileStream(@"c:\Temp\birthdays.xls", FileMode.Open))
  {
    var fs = new POIFSFileSystem(stream);
    workbook = new HSSFWorkbook(fs);
  }

  // now get the worksheet that has the birthdays; I am just using the first sheet
  var birthdaySheet = workbook.GetSheetAt(0);

  // we are going to populate a list of Birthday objects in memory that we can then sort and write back into the file;
  // the Birthday class is defined below
  var birthdays = new Collection<Birthday>();
  for (int i = 0; i < birthdaySheet.LastRowNum; i++) // the LastRowNum property is very useful!
  {
    birthdays.Add(new Birthday
                    {
                      Name = birthdaySheet.GetRow(i).GetCell(0).StringCellValue, // name is in column A, which is 0
                      Bday = birthdaySheet.GetRow(i).GetCell(1).NumericCellValue // birthday is in column B, which is 1
                    });
  }

  // now we sort the birthdays
  var sorted = birthdays.OrderBy(b => b.Name).ToArray();

  // now we go back through the cells and write over the values with the sorted values
  for (int i = 0; i < sorted.Length; i++)
  {
    birthdaySheet.GetRow(i).GetCell(0).SetCellValue(sorted[i].Name);
    birthdaySheet.GetRow(i).GetCell(1).SetCellValue(sorted[i].Bday);
  }

  // finally, save the workbook
  using (var stream = new FileStream(@"c:\temp\birthdays.xls", FileMode.Truncate))
  {
    workbook.Write(stream);
  }

生日班:

class Birthday
{
  public string Name { get; set; }
  public double Bday { get; set; }
}
于 2013-06-04T02:13:37.840 回答