I'm creating an autofilter on an XSSFSheet as follows:
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?
Thanks! Sam
Class XSSFSheet. High level representation of a SpreadsheetML worksheet. Sheets are the central structures within a workbook, and are where a user does most of his spreadsheet work. The most common type of sheet is the worksheet, which is represented as a grid of cells.
HSSFWorkbook − This class has methods to read and write Microsoft Excel files in . xls format. It is compatible with MS-Office versions 97-2003. XSSFWorkbook − This class has methods to read and write Microsoft Excel and OpenOffice xml files in .
To Hide a row or column, Apache POI SS provide Row. setZeroHeight(boolean) method.
Create two CellStyles, one with setLocked(true) and other with setLocked(false). Then apply the locked style for all the cells in the column which needs to be locked, and the unlocked style for all the other cells. Protect the sheet using sheet. protectSheet("");
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);
Reference: : https://asposeapachepoi.codeplex.com/wikipage?title=Sort%20Data.
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 list ascendingly. Something like this: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:
Collections.sort(yourList<MyRow>);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With