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

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

问题描述

我想用字符串列的一个行的表进行排序。我试过才达到,使用Sheet.shiftRows方法,但我不能与管理。它不会在我的方法切换的行位置。什么是错误的,我code?或者,也许有更好的方式来在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?

推荐答案

现在我现在为什么它不工作。有一个在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

更新
这个bug已经从3.9版本的固定

UPDATE This bug has been fixed from version 3.9

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

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