Created
February 27, 2019 04:54
-
-
Save marcoblos/cbaa817be4da7b605b315c84fb2c1451 to your computer and use it in GitHub Desktop.
Simple excel file reader with spring rest controller
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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