Apache-POI在excel中排序行 [英] Apache-POI sorting rows in excel

查看:282
本文介绍了Apache-POI在excel中排序行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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版修正

UPDATE This bug has been fixed from version 3.9

这篇关于Apache-POI在excel中排序行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆