Wednesday, August 2, 2017

Upload Excel file using Rest api

Upload an excel file to Rest web service or Rest API.
Below code, snipat works for both .xls and .xlsx file format.
You can send the file as request parameter and the same name should be passed by calling service (Postman, Ajax etc,)

@RequestMapping(method = RequestMethod.POST, value = "/uploadBulkUsers")
public void uploadBulkUsers(@RequestParam("file") MultipartFile file , @QueryParam("smId") Integer smId) {
LOGGER.info("file.getSize();" + file.getSize());
LOGGER.info("file " + file.getOriginalFilename());
LOGGER.info("smId  " + smId);
try {
Workbook workbook = WorkbookFactory.create(file.getInputStream());
Sheet datatypeSheet = workbook.getSheetAt(0);
Iterator<Row> iterator = datatypeSheet.iterator();
while (iterator.hasNext()) {
Row currentRow = iterator.next();
Iterator<org.apache.poi.ss.usermodel.Cell> cellIterator = currentRow.iterator();

while (cellIterator.hasNext()) {

org.apache.poi.ss.usermodel.Cell currentCell = cellIterator.next();
// getCellTypeEnum shown as deprecated for version 3.15
// getCellTypeEnum ill be renamed to getCellType starting
// from version 4.0
if (currentCell.getCellTypeEnum() == CellType.STRING) {
System.out.print(currentCell.getStringCellValue() + "&&");
} else if (currentCell.getCellTypeEnum() == CellType.NUMERIC) {
System.out.print(currentCell.getNumericCellValue() + "&&");
}
}
System.out.println();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (EncryptedDocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}


No comments:

Post a Comment