java XSSFSheet (Apache POI) 排序和过滤
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26718371/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
XSSFSheet (Apache POI) sorting and filtering
提问by user3250532
I'm creating an autofilter on an XSSFSheet as follows:
我正在 XSSFSheet 上创建一个自动过滤器,如下所示:
sheet.setAutoFilter(new CellRangeAddress(1, sheet.getLastRowNum() + 1,
0, 14));
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 列)上的值升序排序。有人知道怎么做吗?
Thanks! Sam
谢谢!山姆
回答by Fred Silva
1. Sorting with ASPOSE library
1.用ASPOSE库排序
Currently, there is no sorting available for Apache POI. I suggest ASPOSE Java for Apache POI. With that library, your class would look like:
目前,Apache POI 没有可用的排序。我建议为 Apache POI 使用 ASPOSE Java。使用该库,您的类将如下所示:
//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);
Reference: : https://asposeapachepoi.codeplex.com/wikipage?title=Sort%20Data.
参考:https://asposeapachepoi.codeplex.com/wikipage?title=Sort%20Data。
2. With Java Collections.sort()
2. 使用 Java 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
. Override the method java.lang.Comparable
with your criteria and use compareTo
to sort your listascendingly. Something like this:Collections.sort()
如果您不想或不能像我一样使用 ASPOSE,您可以创建一个类来表示源文件中的数据行,该类实现了
. java.lang.Comparable
使用您的条件覆盖该方法并用于compareTo
对您的列表进行升序排序。像这样的东西:Collections.sort()
//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);
}
}
Then, in your main class (or the class that you want to sort you list of MyRow in), you would code:
然后,在您的主类(或您想要对 MyRow 列表进行排序的类)中,您将编码:
Collections.sort(yourList<MyRow>);