按列排序excel - Apache POI

时间:2018-03-28 12:27:00

标签: java excel apache-poi

我有XSSFWorkbook个n列。我的要求是按第一列对整张纸进行排序。 我提到了这个link,但没有得到有关排序的任何信息。

我还尝试了here中的代码,但它在

处提供了异常
sheet.shiftRows(row2.getRowNum(), row2.getRowNum(), -1);

我正在使用Apache POI 3.17

任何人都有任何建议或解决方案吗?

1 个答案:

答案 0 :(得分:1)

在更改列时,POI中似乎存在错误,他们说它已在3.9中修复,但我使用3.17仍然拥有它:

Exception in thread "main" org.apache.xmlbeans.impl.values.XmlValueDisconnectedException
at org.apache.xmlbeans.impl.values.XmlObjectBase.check_orphaned(XmlObjectBase.java:1258)
at org.openxmlformats.schemas.spreadsheetml.x2006.main.impl.CTRowImpl.getR(Unknown Source)
at org.apache.poi.xssf.usermodel.XSSFRow.getRowNum(XSSFRow.java:394)
...

我认为它和你一样。所以我想出了另一种方式:

对行进行排序,然后创建新工作簿并按正确顺序复制行。 然后将此已排序的工作簿写入原始文件。

为简单起见,我假设所有单元格值都是字符串。 (如果没有,则相应地修改)

private static final String FILE_NAME = "/home/userName/Workspace/fileToSort.xlsx";

public static void main(String[] args) throws Exception {

    //create a workbook from your file
    FileInputStream excelFile = new FileInputStream(new File(FILE_NAME));
    Workbook originalWorkbook = new XSSFWorkbook(excelFile);
    Sheet originalSheet = originalWorkbook.getSheetAt(0);

    // Create a SortedMap<String, Row> where the key is the value of the first column
    // This will automatically sort the rows
    Map<String, Row> sortedRowsMap = new TreeMap<>();
    Iterator<Row> rowIterator = originalSheet.rowIterator();
    while(rowIterator.hasNext()) {
        Row row = rowIterator.next();
        sortedRowsMap.put(row.getCell(0).getStringCellValue(), row);
    }

    // Create a new workbook
    Workbook sortedWorkbook = new XSSFWorkbook();
    Sheet sortedSheet = sortedWorkbook.createSheet(originalSheet.getSheetName());

    // Copy all the sorted rows to the new workbook
    int rowIndex = 0;
    for(Row row : sortedRowsMap.values()) {
        Row newRow = sortedSheet.createRow(rowIndex);
        copyRowToRow(row, newRow);
        rowIndex++;
    }

    // Write your new workbook to your file
    try(FileOutputStream out = new FileOutputStream(FILE_NAME)) {
        sortedWorkbook.write(out);
    } catch (FileNotFoundException ex) {
        ex.printStackTrace();
    }
}


// Utility method to copy rows
private static void copyRowToRow(Row row, Row newRow) {
    Iterator<Cell> cellIterator = row.cellIterator();
    int cellIndex = 0;
    while(cellIterator.hasNext()) {
        Cell cell = cellIterator.next();
        Cell newCell = newRow.createCell(cellIndex);
        newCell.setCellValue(cell.getStringCellValue());
        cellIndex++;
    }
}

我在以下文件中尝试了

A    B
--------
a   one
c   three
d   four
b   two

并以这种方式对其进行排序:

A    B
--------
a   one
b   two
c   three 
d   four