Uploading EXCEL - 2003, 2007 file's using file uploading UI, and insert all file data into database.
<form:form modelAttribute="bulkfileupload" role="form" enctype="multipart/form-data" >
<div class="form-group">
<label>Upload Excel File !</label>
<form:input type="file" path="uploadFile" id="uploadFile" />
<div class="has-error">
<form:errors path="uploadFile" class="help-inline" />
</div>
</div>
<div class="form-group">
<input type="submit" value="upload">
</div>
</form:form>
For handling request of multipart/form-data, required MultipartResolver interface to handle file request. for that configure bean tage in xml file or
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- max upload size in bytes -->
<property name="maxUploadSize" value="20971520" />
<!-- max size of file in memory (in bytes) -->
<property name="maxInMemorySize" value="1048576" />
</bean>
OR
@Bean
public MultipartResolver multipartResolver() {
return new StandardServletMultipartResolver();
}
method in appconfig class. And in Dispatcher class add this method
@Override
protected void customizeRegistration(ServletRegistration.Dynamic registration) {
// upload temp file will put here
File uploadDirectory = new File(System.getProperty("java.io.tmpdir"));
// register a MultipartConfigElement
MultipartConfigElement multipartConfigElement =
new MultipartConfigElement(uploadDirectory.getAbsolutePath(),
maxUploadSizeInMb, maxUploadSizeInMb * 2, maxUploadSizeInMb / 2);
registration.setMultipartConfig(multipartConfigElement);
}
On the basis of initializer of spring mvc configuration. we handle file type request.
/**
* @author wasimansari
* Bulk file uploading using direct action to uploading bulk data into database!
* */
@RequestMapping(value = {"/uploadbulkfilestudents"} , method=RequestMethod.POST)
public String uploadingStudentDetails(@Valid @ModelAttribute(value="bulkfileupload")UploadMultipartBulkFile uploadFile,
BindingResult result, ModelMap model){
System.out.println(uploadFile.getUploadFile().getOriginalFilename()+ " file uploading");
if (result.hasErrors() || uploadFile.getUploadFile().getOriginalFilename().equalsIgnoreCase("")) {
FieldError ssoError =new FieldError("bulkfileupload","uploadFile",messageSource.getMessage("non.bulkfileupload.uploadFile", new String[]{uploadFile.getUploadFile().toString()}, Locale.getDefault()));
result.addError(ssoError);
return "user/uploadstudentdetails";
}
String fileName = uploadFile.getUploadFile().getOriginalFilename();
String fileExtensionName = fileName.substring(fileName.indexOf("."));
try {
List<StudentProfileDTO> lstUser = new ArrayList<>();
int i = 0;
if(fileExtensionName.equalsIgnoreCase(".xlsx")) {
XSSFWorkbook workbook = UserApplicationUtils.readXLSXFile2007(uploadFile);
XSSFSheet worksheet = workbook.getSheetAt(0);
while (i <= worksheet.getLastRowNum()) {
StudentProfileDTO studentProfile = new StudentProfileDTO();
XSSFRow row = worksheet.getRow(i++);
studentProfile.setStudentname(row.getCell(0).getStringCellValue());
studentProfile.setStudentmobileno( NumberToTextConverter.toText(row.getCell(1).getNumericCellValue() ) );
studentProfile.setStudentemailid(row.getCell(2).getStringCellValue());
studentProfile.setStudentdob(String.valueOf( UserApplicationUtils.formatedTimeStamp(row.getCell(3).getDateCellValue()) ));
XSSFCell emptyCell = row.getCell(4);
if(null == emptyCell || emptyCell.getCellType() == Cell.CELL_TYPE_BLANK) {
studentProfile.setStudentaddress("");
}else {
studentProfile.setStudentaddress(emptyCell.getStringCellValue());
}
// set value to mantain database col
studentProfile.setAuthorname(new AuthSecurityUser().getPrincipal());
studentProfile.setStdcreateddate(new Date(System.currentTimeMillis()));
studentProfile.setStdIsActive(true);
lstUser.add(studentProfile);
}
workbook.close();
}else if(fileExtensionName.equalsIgnoreCase(".xls")) {
HSSFWorkbook workbook2003 = UserApplicationUtils.readXLSFile2003(uploadFile);
HSSFSheet sheet = workbook2003.getSheetAt(0);
while (i <= sheet.getLastRowNum()) {
StudentProfileDTO studentProfile = new StudentProfileDTO();
HSSFRow row = (HSSFRow) sheet.getRow(i++);
studentProfile.setStudentname(row.getCell(0).getStringCellValue());
studentProfile.setStudentmobileno( NumberToTextConverter.toText(row.getCell(1).getNumericCellValue() ) );
studentProfile.setStudentemailid(row.getCell(2).getStringCellValue());
studentProfile.setStudentdob(String.valueOf( UserApplicationUtils.formatedTimeStamp(row.getCell(3).getDateCellValue()) ));
HSSFCell emptyCell = row.getCell(4);
if(null == emptyCell || emptyCell.getCellType() == Cell.CELL_TYPE_BLANK) {
studentProfile.setStudentaddress("");
}else {
studentProfile.setStudentaddress(emptyCell.getStringCellValue());
}
// set value to mantain database col
studentProfile.setAuthorname(new AuthSecurityUser().getPrincipal());
studentProfile.setStdcreateddate(new Date(System.currentTimeMillis()));
studentProfile.setStdIsActive(true);
lstUser.add(studentProfile);
}
workbook2003.close();
}else {
FieldError ssoError =new FieldError("bulkfileupload","uploadFile",messageSource.getMessage("nonrighttype.bulkfileupload.uploadFile", new String[]{uploadFile.getUploadFile().toString()}, Locale.getDefault()));
result.addError(ssoError);
return "user/uploadstudentdetails";
}
boolean status = userProfileDetailsService.uploadAllStudentProfileDetails(lstUser);
if(status) {
model.addAttribute("lstUser", lstUser);
}
}catch(Exception ex) {
ex.printStackTrace();
}
model.addAttribute("loggedinuser", new AuthSecurityUser().getPrincipal());
return "user/uploadstudentdetails";
}
<form:form modelAttribute="bulkfileupload" role="form" enctype="multipart/form-data" >
<div class="form-group">
<label>Upload Excel File !</label>
<form:input type="file" path="uploadFile" id="uploadFile" />
<div class="has-error">
<form:errors path="uploadFile" class="help-inline" />
</div>
</div>
<div class="form-group">
<input type="submit" value="upload">
</div>
</form:form>
For handling request of multipart/form-data, required MultipartResolver interface to handle file request. for that configure bean tage in xml file or
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- max upload size in bytes -->
<property name="maxUploadSize" value="20971520" />
<!-- max size of file in memory (in bytes) -->
<property name="maxInMemorySize" value="1048576" />
</bean>
OR
@Bean
public MultipartResolver multipartResolver() {
return new StandardServletMultipartResolver();
}
method in appconfig class. And in Dispatcher class add this method
@Override
protected void customizeRegistration(ServletRegistration.Dynamic registration) {
// upload temp file will put here
File uploadDirectory = new File(System.getProperty("java.io.tmpdir"));
// register a MultipartConfigElement
MultipartConfigElement multipartConfigElement =
new MultipartConfigElement(uploadDirectory.getAbsolutePath(),
maxUploadSizeInMb, maxUploadSizeInMb * 2, maxUploadSizeInMb / 2);
registration.setMultipartConfig(multipartConfigElement);
}
On the basis of initializer of spring mvc configuration. we handle file type request.
/**
* @author wasimansari
* Bulk file uploading using direct action to uploading bulk data into database!
* */
@RequestMapping(value = {"/uploadbulkfilestudents"} , method=RequestMethod.POST)
public String uploadingStudentDetails(@Valid @ModelAttribute(value="bulkfileupload")UploadMultipartBulkFile uploadFile,
BindingResult result, ModelMap model){
System.out.println(uploadFile.getUploadFile().getOriginalFilename()+ " file uploading");
if (result.hasErrors() || uploadFile.getUploadFile().getOriginalFilename().equalsIgnoreCase("")) {
FieldError ssoError =new FieldError("bulkfileupload","uploadFile",messageSource.getMessage("non.bulkfileupload.uploadFile", new String[]{uploadFile.getUploadFile().toString()}, Locale.getDefault()));
result.addError(ssoError);
return "user/uploadstudentdetails";
}
String fileName = uploadFile.getUploadFile().getOriginalFilename();
String fileExtensionName = fileName.substring(fileName.indexOf("."));
try {
List<StudentProfileDTO> lstUser = new ArrayList<>();
int i = 0;
if(fileExtensionName.equalsIgnoreCase(".xlsx")) {
XSSFWorkbook workbook = UserApplicationUtils.readXLSXFile2007(uploadFile);
XSSFSheet worksheet = workbook.getSheetAt(0);
while (i <= worksheet.getLastRowNum()) {
StudentProfileDTO studentProfile = new StudentProfileDTO();
XSSFRow row = worksheet.getRow(i++);
studentProfile.setStudentname(row.getCell(0).getStringCellValue());
studentProfile.setStudentmobileno( NumberToTextConverter.toText(row.getCell(1).getNumericCellValue() ) );
studentProfile.setStudentemailid(row.getCell(2).getStringCellValue());
studentProfile.setStudentdob(String.valueOf( UserApplicationUtils.formatedTimeStamp(row.getCell(3).getDateCellValue()) ));
XSSFCell emptyCell = row.getCell(4);
if(null == emptyCell || emptyCell.getCellType() == Cell.CELL_TYPE_BLANK) {
studentProfile.setStudentaddress("");
}else {
studentProfile.setStudentaddress(emptyCell.getStringCellValue());
}
// set value to mantain database col
studentProfile.setAuthorname(new AuthSecurityUser().getPrincipal());
studentProfile.setStdcreateddate(new Date(System.currentTimeMillis()));
studentProfile.setStdIsActive(true);
lstUser.add(studentProfile);
}
workbook.close();
}else if(fileExtensionName.equalsIgnoreCase(".xls")) {
HSSFWorkbook workbook2003 = UserApplicationUtils.readXLSFile2003(uploadFile);
HSSFSheet sheet = workbook2003.getSheetAt(0);
while (i <= sheet.getLastRowNum()) {
StudentProfileDTO studentProfile = new StudentProfileDTO();
HSSFRow row = (HSSFRow) sheet.getRow(i++);
studentProfile.setStudentname(row.getCell(0).getStringCellValue());
studentProfile.setStudentmobileno( NumberToTextConverter.toText(row.getCell(1).getNumericCellValue() ) );
studentProfile.setStudentemailid(row.getCell(2).getStringCellValue());
studentProfile.setStudentdob(String.valueOf( UserApplicationUtils.formatedTimeStamp(row.getCell(3).getDateCellValue()) ));
HSSFCell emptyCell = row.getCell(4);
if(null == emptyCell || emptyCell.getCellType() == Cell.CELL_TYPE_BLANK) {
studentProfile.setStudentaddress("");
}else {
studentProfile.setStudentaddress(emptyCell.getStringCellValue());
}
// set value to mantain database col
studentProfile.setAuthorname(new AuthSecurityUser().getPrincipal());
studentProfile.setStdcreateddate(new Date(System.currentTimeMillis()));
studentProfile.setStdIsActive(true);
lstUser.add(studentProfile);
}
workbook2003.close();
}else {
FieldError ssoError =new FieldError("bulkfileupload","uploadFile",messageSource.getMessage("nonrighttype.bulkfileupload.uploadFile", new String[]{uploadFile.getUploadFile().toString()}, Locale.getDefault()));
result.addError(ssoError);
return "user/uploadstudentdetails";
}
boolean status = userProfileDetailsService.uploadAllStudentProfileDetails(lstUser);
if(status) {
model.addAttribute("lstUser", lstUser);
}
}catch(Exception ex) {
ex.printStackTrace();
}
model.addAttribute("loggedinuser", new AuthSecurityUser().getPrincipal());
return "user/uploadstudentdetails";
}