0

Excel ファイルから重複行を削除しようとしています。次のコード行があります。コードを実行すると、modified_excel.xls が作成されます。ただし、このファイルを開くと「サポートされていないファイル形式」というエラーが表示されます

Workbook sourceDocument = Workbook.getWorkbook(new File("C:\\source.xls"));
WritableWorkbook writableTempSource = Workbook.createWorkbook(new File("C:\\excel\\modified_excel.xls"), sourceDocument);
WritableSheet sourceSheet = writableTempSource.getSheet(0);
String previousContent = "";
for (int i = 7; i < sourceSheet.getRows(); i++) {
     String currentContent = sourceSheet.getCell(0, i).getContents();
     if(!currentContent.equals(previousContent)){
         sourceSheet.removeRow(i);
     }
     previousContent = currentContent;
}
writableTempSource.close();
sourceDocument.close();
4

1 に答える 1

2

There are two things I think which can help this situation

1)

writableTempSource.write();

This should come just before closing writableTempSource. If you were to comment out the for block, you would see you still have a file created of an "unsupported format". This line will fix that.

2)

I do believe you may have issue with the i variable in the for loop. Consider this. You are checking sourceSheet.getRows() on each iteration. However, if rows are getting deleted, then this value changes each time a deletion occurs. The result is that you may be skipping lines which is not necessary what you want. Java naturally provides this on for loops with ConcurrentModificationException, however in the magical kingdom of API-Land, it looks like you are not protected from doing this sort of thing.

于 2012-09-17T16:13:46.517 に答える