XSSFSheet(Apache POI)排序和过滤 [英] XSSFSheet (Apache POI) sorting and filtering
问题描述
我正在XSSFSheet上创建自动过滤器,如下所示:
I'm creating an autofilter on an XSSFSheet as follows:
sheet.setAutoFilter(new CellRangeAddress(1, sheet.getLastRowNum() + 1,
0, 14));
它工作得很好,但是我也希望它默认为通过对特定列(从零开始索引的第1列)上的值进行升序排序.有人知道怎么做吗?
It works just fine, but I'd also like it to default to sorting by ascending values on a particular column (column 1 as indexed from zero). Anybody know how to do that?
谢谢!山姆
推荐答案
1.用ASPOSE库排序
当前,没有针对Apache POI的排序.我建议将ASPOSE Java用于Apache POI.使用该库,您的类将如下所示:
1. Sorting with ASPOSE library
Currently, there is no sorting available for Apache POI. I suggest ASPOSE Java for Apache POI. With that library, your class would look like:
//Obtain the DataSorter object in the workbook
DataSorter sorter = workbook.getDataSorter();
//Set the first order
sorter.setOrder1(SortOrder.ASCENDING);
//Define the first key.
sorter.setKey1(0);
//Set the second order
sorter.setOrder2(SortOrder.ASCENDING);
//Define the second key
sorter.setKey2(1);
//Create a cells area (range).
CellArea ca = new CellArea();
//Specify the start row index.
ca.StartRow = 1;
//Specify the start column index.
ca.StartColumn = 0;
//Specify the last row index.
ca.EndRow = 9;
//Specify the last column index.
ca.EndColumn = 2;
//Sort data in the specified data range (A2:C10)
sorter.sort(cells, ca);
参考:: https://asposeapachepoi.codeplex.com/wikipage?title=排序%20Data .
如果像我一样不想或不能使用ASPOSE,则可以创建一个表示源文件中数据行的类,该类实现
java.lang.Comparable 代码>
.使用您的条件覆盖方法
,并使用 compareTo
Collections.sort()
If you don't want to or can't use ASPOSE, like me, you could create a class that represents a data row in your source file, which implements java.lang.Comparable
. Override the method compareTo
with your criteria and use Collections.sort()
to sort your list ascendingly. Something like this:
//imports omitted
public class MyRow implements Comparable<MyRow>{
private String column1;
private int column2;
@Override
public int compareTo(MyRow o) {
return this.column1.compareTo(o.column2);
}
}
然后,在您的主类(或要对MyRow列表进行排序的类)中,您将进行编码:
Then, in your main class (or the class that you want to sort you list of MyRow in), you would code:
Collections.sort(yourList<MyRow>);
这篇关于XSSFSheet(Apache POI)排序和过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!