我来自这个主题:Apache-POI sorting rows in excel
这是我的代码:
public class WorkWithData {
private int rowNum;
private Sheet sheet;
private Workbook workbook;
protected WorkWithData(File userFile) throws Exception {
this.workbook = getWorkbook(userFile);
sheet = workbook.getSheetAt(0);
rowNum = sheet.getLastRowNum();
}
protected Workbook getWorkbook(File userFile) throws Exception {
InputStream inputStream = new FileInputStream(userFile);
return WorkbookFactory.create(inputStream);
}
public void saveWorkbook(File userFile) throws IOException {
OutputStream outputStream = new FileOutputStream(userFile);
workbook.write(outputStream);
}
public void sortSheet() throws IOException {
boolean sorted = true;
while (sorted) {
sorted = false;
for (Row row : sheet) {
if (row.getRowNum() == rowNum) {
break;
}
if (row.getRowNum() == 0) {
continue;
}
Row row2 = sheet.getRow(row.getRowNum() + 1);
if (row2 == null) {
continue;
}
String firstValue = (row.getCell(0) != null) ? row.getCell(0).getStringCellValue() : "";
String secondValue = (row2.getCell(0) != null) ? row2.getCell(0).getStringCellValue() : "";
if (secondValue.compareToIgnoreCase(firstValue) < 0) {
sheet.shiftRows(row2.getRowNum(), row2.getRowNum(), -1);
sheet.shiftRows(row.getRowNum(), row.getRowNum(), 1);
sorted = true;
lookAtFile();
}
}
}
saveWorkbook(new File("newnwe.xlsx"));
}
private void lookAtFile() {
System.out.println("NEW OUTPUT:");
Sheet sheet1 = workbook.cloneSheet(0);
for (int i = 0; i <= rowNum; i++) {
System.out.println(sheet1.getRow(i).getCell(0).getStringCellValue() + " : " + sheet1.getRow(i).getCell(1).getStringCellValue());
}
}
}
在我们“更改”文件后,我已在colsole上输出结果。
输出:
NEW OUTPUT:
Char name : Env name
Andrew : PC
Andrew : PC
Other name : Notebook
Andrew : PC
Other name : Notebook
Other name : Notebook
Other name : Notebook
Other name : Notebook
Other name : Notebook
Andrew : PC
Other name : Notebook
NEW OUTPUT:
Char name : Env name
Andrew : PC
Andrew : PC
Other name : Notebook
Andrew : PC
Other name : Notebook
Other name : Notebook
Other name : Notebook
Other name : Notebook
Other name : Notebook
Andrew : PC
Other name : Notebook
正如您所看到的,没有任何变化。我预计第一列将首先安德鲁4次,然后是其他名称。
我期待错误的结果吗?它应该如何运作?
为什么shiftRows()不会改变任何东西?