In this method i used xssf class which is used to read xlsx file but we cant do it for xls file.for xls we need to have Hssf class .User can import any format there .My requirement,Is there any Class that can be used instead of xssf and hssf to read both kind of file. in my example i used xssf.
@RequestMapping(value="/import",method = RequestMethod.POST)
public ModelAndView imports(Model model, @RequestParam("excelFile") MultipartFile excelfile){
try {
List<DepartmentModel> lstUser = new ArrayList<>();
int i = 0;
XSSFWorkbook workbook = new XSSFWorkbook(excelfile.getInputStream());
XSSFSheet worksheet = workbook.getSheetAt(0);
while (i <= worksheet.getLastRowNum()) {
DepartmentModel user = new DepartmentModel();
XSSFRow row = worksheet.getRow(i++);
user.setHrName(row.getCell(0).getStringCellValue());
user.setDepartmentName(row.getCell(1).getStringCellValue());
user.setParentDepartment(row.getCell(2).getStringCellValue());
lstUser.add(user);
}
departmentService.updateList(lstUser);
model.addAttribute("lstUser", lstUser);
} catch (Exception e) {
e.printStackTrace();
}
return new ModelAndView("redirect:/listOfDepartment");
}
Im having another method which i used Hssf to read xls file.But iam having only one import button user can upload any type of file xls,xlsx but for import button i can have one action eigther go to xssf or hssf method.So i like to know is there any possible way to have botth in single method.Or any other super class to having property of both Xssf and Hssf Class.
For supporting both
HSSFas well asXSSFfor reading and rewriting*.xlsand*.xlsx, you will using WorkbookFactory for creating Workbook. This is able creatingWorkbookfromInputStreamof*.xlsas well as of*.xlsxfiles.Then, as long as possible, you will working with the interfaces of Package org.apache.poi.ss.usermodel instead of the special
HSSForXSSFclasses.This is not always possible since
apache poiis in development until now. But if not possible you can detect viainstanceofwhat object (HSSForXSSF) you really are working with.And for writing you will using the appropriate methods dependent of the
instanceoftheWorkbook.Up to
apache poi 3.17Workbook.writehas closed theOutputStream. Now inapache poi 4.0.*versions it not more closes theOutputStream. So we need using