Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save marcoblos/cbaa817be4da7b605b315c84fb2c1451 to your computer and use it in GitHub Desktop.
Save marcoblos/cbaa817be4da7b605b315c84fb2c1451 to your computer and use it in GitHub Desktop.
Simple excel file reader with spring rest controller
private String getContent(Cell cell) {
switch (cell.getCellTypeEnum()) {
case STRING:
return cell.getRichStringCellValue().getString();
case NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
return cell.getDateCellValue() + "";
} else {
return cell.getNumericCellValue() + "";
}
case BOOLEAN:
return cell.getBooleanCellValue() + "";
case FORMULA:
return cell.getCellFormula() + "";
default:
return "";
}
}
@PostMapping("/upload-excel-file")
public void uploadExcelFile(Model model, MultipartFile file) throws IOException {
InputStream in = file.getInputStream();
try (XSSFWorkbook xssfWorkbook = new XSSFWorkbook(in)) {
Sheet sheet = xssfWorkbook.getSheetAt(0);
List<Produto> produtos = new ArrayList<Produto>();
for (Row row : sheet) {
if (row.getRowNum() != 0) {
String name = getContent(row.getCell(0));
String description = getContent(row.getCell(1));
// ...
// ...
}
}
service.save(produtos);
} catch (Exception e) {
throw e;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment