在Excel中的Apache-POIsorting行

我想通过一个string列排列表中的行。 我试图实现使用Sheet.shiftRows方法,但我无法pipe理。 它不会在我的方法中切换行的位置。 我的代码有什么问题? 或者也许有更好的方法来sorting在Excel中的任何string列的行?

/** * Sorts (AZ) 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; } } } } 

任何想法如何pipe理表中的行sorting?

更新上面的方法自Apache-POI 3.9版本起作用。

编辑:添加缺less括号–helvio

Poi没有内置的sorting机制,当然你还远远没有满足这个需求。

我想你正在陷入麻烦,因为你正在移动你正在迭代的行。 我已经运行了上面的代码,看起来正在发生的事情是,行正在代码执行结束时从工作表中消失。

该问题试图对读入表进行就地修改。 我相信创build第二个输出表会更合适。

所以基本的方法是读取表单,在java中sorting,就像处理其他sorting问题一样,写入输出表。 如果您创build的行号映射对于您感兴趣的列的string值是唯一的,那么您可以按照值对映射进行sorting。 如果您只是预见到需要对单个列进行sorting,那么这种方法就行得通了。 无论如何,这不像从Excel中selectsorting菜单选项那么简单。

现在我现在为什么不工作。 shiftRows方法有一个错误。 当第三个参数(移动的行数)为负时,会引起麻烦。

这在这里描述: https : //issues.apache.org/bugzilla/show_bug.cgi?id=53798

更新这个bug已经从版本3.9修复