Apache-POI在excel中排序行

rob*_*son 12 java sorting excel row apache-poi

我想用一个字符串列对表中的行进行排序.我尝试使用Sheet.shiftRows方法实现这一点,但我无法管理.它不会在我的方法中切换行的位置.我的代码有什么问题?或者也许有更好的方法来排序excel中任何String列的行?

/**
 * Sorts (A-Z) rows by String column
 * @param sheet - sheet to sort
 * @param column - String column to sort by
 * @param rowStart - sorting from this row down
 */
private void sortSheet(Sheet sheet, int column, int rowStart) {
    boolean sorting = true;
    int lastRow = sheet.getLastRowNum();
    while (sorting == true) {
        sorting = false;
        for (Row row : sheet) {
            // skip if this row is before first to sort
            if (row.getRowNum()<rowStart) continue;
            // end if this is last row
            if (lastRow==row.getRowNum()) break;
            Row row2 = sheet.getRow(row.getRowNum()+1);
            if (row2 == null) continue;
            String firstValue = (row.getCell(column) != null) ? row.getCell(column).getStringCellValue() : "";
            String secondValue = (row2.getCell(column) != null) ? row2.getCell(column).getStringCellValue() : "";
            //compare cell from current row and next row - and switch if secondValue should be before first
            if (secondValue.compareToIgnoreCase(firstValue)<0) {                    
                sheet.shiftRows(row2.getRowNum(), row2.getRowNum(), -1);
                sheet.shiftRows(row.getRowNum(), row.getRowNum(), 1);
                sorting = true;
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

知道如何管理工作表中的行排序吗?

更新上述方法自Apache-POI 3.9版本起作用.

编辑:添加了缺失的括号--helvio

dem*_*lem 6

Poi没有内置的排序机制,尽管您当然与第一个有这种需求的人相去甚远。

我认为您遇到了麻烦,因为正在移动要迭代的行。我已经运行了上面的代码,似乎正在发生的事情是,在代码执行结束时,行从表中消失了。

该问题试图对已读工作表进行就地修改。我认为创建第二个输出表会更合适。

因此,基本方法是读取工作表,像对待其他排序问题一样在Java中进行排序,然后写入输出工作表。如果您对感兴趣的列的字符串值进行了唯一的行号映射,则可以按值对映射进行排序。如果您仅预见到需要对单个列进行排序,则这种方法将起作用。无论如何,这并不像从excel中选择排序菜单选项那样简单。


rob*_*son 2

现在我现在知道为什么它不起作用了。shiftRows 方法存在错误。当第三个参数(要移动的行数)为负数时,会引起麻烦。

此处描述:https ://issues.apache.org/bugzilla/show_bug.cgi?id=53798

更新 该bug已从3.9版本修复