XSSFSheet(Apache POI)排序和过滤

use*_*532 5 java

我在XSSFSheet上创建一个自动过滤器,如下所示:

sheet.setAutoFilter(new CellRangeAddress(1, sheet.getLastRowNum() + 1,
                0, 14));
Run Code Online (Sandbox Code Playgroud)

它工作正常,但我也希望它默认按特定列上的升序值排序(第1列从零开始索引).有谁知道怎么做?

谢谢!山姆

Fre*_*lva 8

1.使用ASPOSE库排序

目前,Apache POI没有可用的排序.我建议ASPOSE Java用于Apache POI.使用该库,您的课程将如下所示:



    //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=Sort%20Data.

2.使用Java 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,在您的主类(或您想要对MyRow列表进行排序的类)中,您将编写代码:

Collections.sort(yourList<MyRow>);
Run Code Online (Sandbox Code Playgroud)