如何使用NPOI库在C#中对excel中的数据进行排序

时间:2013-06-03 16:38:48

标签: c# excel sorting npoi

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

excel电子表格非常简单。标题有两列,"名称"(列A)和"生日"(列B)。数据绝不排序。

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

我将如何这样做?

1 个答案:

答案 0 :(得分:2)

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

  // 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; }
}