Apache POI:按日期对行进行排序

Den*_* M. 2 java sorting excel apache-poi

我正在使用Apache POI从XML创建Excel文档。我有一个带有日期值的单元格,我将其设置为日期:

HSSFCellStyle styleDate = workbook.createCellStyle();
HSSFDataFormat dataFormat = workbook.createDataFormat();
styleDate.setDataFormat(dataFormat.getFormat("dd/mm/yyyy Hh:mm"));
styleDate.setAlignment(HorizontalAlignment.CENTER);
Run Code Online (Sandbox Code Playgroud)

Excel中的数据显示为日期。我需要按日期在Excel文档中按日期升序对其进行排序。

我知道POI没有内置的排序功能,并且我不能使用Aspose Cells,因为我没有获得额外许可费用的业务方面的批准。

Excel文件结构:工作表:

1. Item 1: 01/01/2016 (sorted correctly using HashMap sorting)
1.1. Sub item 1: 01/01/2016 02:00 (not sorted, needs to be sorted)
1.2. Sub item 2: 01/01/2016 05:00 (not sorted, needs to be sorted)
1.3. Sub item 3: 01/01/2016 01:00 (not sorted, needs to be sorted)

2. Item 2: 02/01/2016 (sorted correctly using HashMap sorting)
2.1. Sub item 1: 02/01/2016 02:00 (not sorted, needs to be sorted)
2.2. Sub item 2: 02/01/2016 05:00 (not sorted, needs to be sorted)
2.3. Sub item 3: 02/01/2016 01:00 (not sorted, needs to be sorted)
Run Code Online (Sandbox Code Playgroud)

HashMap排序

for (int i = 0; i < nodeList.getLength(); i++) {
    itemHashMap.put(getNodeValue(nodeList, i, "item"),
                                getNodeValue(nodeList, i, "itemDate"));
}
Run Code Online (Sandbox Code Playgroud)

and*_*ied 5

private void sortSheet(Sheet sheet, int column, int rowStart) {
 boolean sorting = true;
 int lastRow = sheet.getLastRowNum();
 while (sorting) {
    sorting = false;
    for (Row row : sheet) {
        if (row.getRowNum() < rowStart) continue;
        if (lastRow == row.getRowNum()) break;
        Row nextRow = sheet.getRow(row.getRowNum() + 1);
        if (nextRow == null) continue;
        Date firstValue = row.getCell(column).getDateCellValue() ;
        Date secondValue = nextRow.getCell(column).getDateCellValue() ;
        if (secondValue.before(firstValue)) {                    
            sheet.shiftRows(nextRow.getRowNum(), nextRow.getRowNum(), -1);
            sheet.shiftRows(row.getRowNum(), row.getRowNum(), 1);
            sorting = true;
        }
    }
 }
}
Run Code Online (Sandbox Code Playgroud)

  • 您是否知道 shiftRows 在使用 -1 时会隐藏上一行或在使用 1 时隐藏底行并且两者都会留下一个空行?。您需要创建一个临时行才能使用该方法。 (2认同)