[英]How to generate Line Chart along with data in excel sheet using NPOI Library c#
[英]How to sort data in excel in C# using NPOI library
如何使用C#和NPOI庫對Excel電子表格中的數據進行排序?
excel電子表格非常簡單。 標題有兩列,“名稱”(列A)和“生日”(列B)。 數據絕不排序。
我的目標是按名稱按字母順序對列表進行排序。 當然,每個名字仍應與正確的生日相匹配。
我該怎么做呢?
這是一個有效的例子。 您需要根據需要為您的文件修改它:
// 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; }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.