我想按字符串列之一对工作表中的行进行排序。我试图使用Sheet.shiftRows方法实现这一点,但是我无法对此进行管理。它不会在我的方法中切换行的位置。我的代码有什么问题?还是有更好的方法可以按Excel中的任何“字符串”列对行进行排序?
/**
* 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()
// 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;
}
}
}
}
任何想法如何管理工作表中的行排序?
更新 上面的方法自Apache-POI 3.9版本开始起作用。
编辑:添加了缺少的括号-helvio