0

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?

Abid
  • 403
  • 4
  • 10
  • 2
    See https://stackoverflow.com/questions/46146161/apache-poi-fileinputstream-works-file-object-fails-nullpointerexception/46149469#46149469. Don't use a `File` to create the workbook. Use a `FileInputStream` instead. – Axel Richter Aug 19 '21 at 12:46
  • @AxelRichter Thanks! That did it! – Abid Aug 19 '21 at 14:10

0 Answers0