Skip to content

Instantly share code, notes, and snippets.

@damiencuvillier
Created April 17, 2023 15:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save damiencuvillier/c5e440704f9ec5af1737b7959d412ec1 to your computer and use it in GitHub Desktop.
Save damiencuvillier/c5e440704f9ec5af1737b7959d412ec1 to your computer and use it in GitHub Desktop.
Java Apache POI simple read / write example
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class XLSXUpdaterExample {
private static final String DIRNAME = "/tmp/";
private XSSFWorkbook workbook;
public XLSXUpdaterExample(String filename) throws IOException, InvalidFormatException {
this.workbook = new XSSFWorkbook(new File(DIRNAME + filename));;
}
private void read() {
XSSFCell cell = this.getMyCell();
double nb = cell.getNumericCellValue();
System.out.printf("February : %2f%n", nb);
}
private void update() throws IOException {
double newValue = 5;
this.getMyCell().setCellValue(newValue);
FileOutputStream fos = new FileOutputStream(new File(DIRNAME + "copy.xlsx"));
workbook.write(fos);
fos.close();
System.out.printf("(after update): %2f%n", newValue);
}
private XSSFCell getMyCell() {
return workbook.getSheetAt(0)
.getRow(2)
.getCell(1);
}
private void close() throws IOException {
workbook.close();
}
public static void main(String[] args) throws IOException, InvalidFormatException {
XLSXUpdaterExample xlsxParser = new XLSXUpdaterExample("simple.xlsx");
xlsxParser.read();
xlsxParser.update();
xlsxParser.close();
xlsxParser = new XLSXUpdaterExample("copy.xlsx");
xlsxParser.read();
xlsxParser.close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment