我想按字符串列之一对工作表中的行进行排序。我试图使用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()<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;
}
}
}
}知道如何管理工作表中的行排序吗?
更新上面的方法可以从ApachePOI3.9版本开始工作。
编辑:添加缺少的括号-helvio
发布于 2012-11-22 05:12:14
现在我知道为什么它不起作用了。shiftRows方法中有一个bug。当第三个参数(要移位的行数)为负数时,就会引起麻烦。
这里描述了这一点:bug.cgi?id=53798
更新这个错误已经从3.9版本中修复了
https://stackoverflow.com/questions/13134490
复制相似问题