patternjavaMinor
Fast edit of Excel file
Viewed 0 times
fasteditfileexcel
Problem
I have this code to edit certain cells in my Excel file using Apache POI, but it is really slow. How can I improved the performance?
Ideally I would like to edit 20000 rows in less than one minute. At the moment it does ~100/min. Any suggestions would be great.
Ideally I would like to edit 20000 rows in less than one minute. At the moment it does ~100/min. Any suggestions would be great.
public static void main(String[] args) throws IOException, InvalidFormatException{
InputStream inp = new FileInputStream("test.xls");
FileOutputStream fileOut = new FileOutputStream("edited-test.xls");
Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt(0);
for(int i=2;i <20002;i++){
Row row = sheet.getRow(i);
Cell cell4 = row.getCell(4);
cell4.setCellValue(i);
Cell cell6 = row.getCell(6);
cell6.setCellValue("aa"+i);
Cell cell8 = row.getCell(8);
cell8.setCellValue("2");
wb.write(fileOut);
System.out.println(i);
}
fileOut.close();
System.out.println("Done!");
}Solution
First thing you should do is only write the file out once, not 20,000 times ;-)
Move the
Additionally, there may be some improvement by reversing the loop:
can become:
This may make some memory management in the API faster.
Move the
wb.write(fileOut); to be outside the loop.....Additionally, there may be some improvement by reversing the loop:
for(int i=2;i <20002;i++){can become:
for(int i=20001;i >= 2;i--){This may make some memory management in the API faster.
Code Snippets
for(int i=2;i <20002;i++){for(int i=20001;i >= 2;i--){Context
StackExchange Code Review Q#41656, answer score: 8
Revisions (0)
No revisions yet.