Using Apache POI, I wonder how to open a xlsx file and save it in a different path without changing the original file.
Code example 1:
// Copy to result path
File mapFile = new File(mapFilePath);
String tempDir = System.getProperty("java.io.tmpdir");
String resultFilePath = Paths.get(tempDir, "result.xlsx").toString();
File resultMapFile = new File(resultFilePath);
Files.copy(mapFile, resultMapFile);
// Open and modify
Workbook mapWb = WorkbookFactory.create(resultMapFile);
mapWb.getSheetAt(0).getRow(1).getCell(1).setCellValue("Test");
mapWb.close();
Workbook original = WorkbookFactory.create(mapFile);
Workbook modified = WorkbookFactory.create(resultMapFile);
System.out.println("Original: " + original.getSheetAt(0).getRow(1).getCell(1).getStringCellValue());
System.out.println("Modified: " + modified.getSheetAt(0).getRow(1).getCell(1).getStringCellValue());
Output:
Original:
Modified:
Code example 2:
// Open
File mapFile = new File(mapFilePath);
Workbook mapWb = WorkbookFactory.create(mapFile);
// Modify
mapWb.getSheetAt(0).getRow(1).getCell(1).setCellValue("Test");
// Save as
String tempDir = System.getProperty("java.io.tmpdir");
String resultFilePath = Paths.get(tempDir, "result.xlsx").toString();
File resultMapFile = new File(resultFilePath);
try (FileOutputStream out = new FileOutputStream(resultMapFile)) {
mapWb.write(out);
}
mapWb.close();
Workbook original = WorkbookFactory.create(mapFile);
Workbook modified = WorkbookFactory.create(resultMapFile);
System.out.println("Original: " + original.getSheetAt(0).getRow(1).getCell(1).getStringCellValue());
System.out.println("Modified: " + modified.getSheetAt(0).getRow(1).getCell(1).getStringCellValue());
Output:
Original: Test
Modified: Test
Question: How do I open a XLSX file, modify it and save it in a different path without changing the original file?