问题描述
我想按字符串列之一对工作表中的行进行排序.我试图使用 Sheet.shiftRows 方法实现这一点,但我无法做到这一点.它不会在我的方法中切换行的位置.我的代码有什么问题?或者也许有更好的方法来按 excel 中的任何字符串列对行进行排序?
I'd like to sort rows in a sheet by one of string column. I tried to achive that using Sheet.shiftRows method, but I cannot manage with that. It doesn't switch positions of rows in my method. What's wrong in my code? Or maybe there is better way to sort rows by any String column in 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;
}
}
}
}
知道如何管理工作表中的行排序吗?
Any idea how to manage row sorting in a sheet?
更新 以上方法从 Apache-POI 3.9 版本开始有效.
UPDATE The method above works since Apache-POI 3.9 version.
添加了缺少的括号 -helvio
Added missing bracket -helvio
推荐答案
现在我知道为什么它不起作用了.shiftRows 方法中有一个错误.当第三个参数(要移动的行数)为负数时,会导致麻烦.
Now I now why it's not working. There is a bug in shiftRows method. When third argument (number of rows to shift) is negative, it causes troubles.
此处描述:https://issues.apache.org/bugzilla/show_bug.cgi?id=53798
更新此错误已从版本 3.9 修复
UPDATEThis bug has been fixed from version 3.9
这篇关于Apache-POI 在 excel 中对行进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!