Ajax上传.xlsx文件并解析
发布时间:2020-12-16 03:02:54 所属栏目:百科 来源:网络整理
导读:1、首先必须配置bean bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" property name="maxUploadSize" value="10485760"/ property name="resolveLazily" value="true"/ property name="maxInMemo
1、首先必须配置bean <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="10485760"/> <property name="resolveLazily" value="true"/> <property name="maxInMemorySize" value="4096"/> <property name="defaultEncoding" value="UTF-8"/> </bean> 2、ftl页面代码 <form id="fileForm" method="post" enctype="multipart/form-data"> <input type="text" id="someText" name="someText"> <input type="file" name="file" id="file"> </form> 3、js代码 var someText= $("#someText").val(); var file = $("#file")[0].files[0]; //获取标签值好像函数与浏览器不兼容,网上的大多是通过$("#file").files[0]获取, 我这里必须通过$("#file")[0].files[0]才能获取到值 var formData = new FormData(); formData.append(‘someText‘,someText); formData.append(‘file‘,file); $.ajax({ type:"post",url:‘请求路径‘,data:formData,dataType:‘json‘,cache:false,contentType: false,processData: false, success: function(data) { // 结果处理 } }); 4、后台代码 @RequestMapping(value = "路径",method = { RequestMethod.GET,RequestMethod.POST })
@ResponseBody
public Object uploadFile(@RequestParam(value = "someText",required = false) String someText,@RequestParam(value = "file",required = false) MultipartFile file,HttpServletRequest request) {//required = false才能获取到值
XSSFWorkbook workbook = new XSSFWorkbook(file.getInputStream());
XSSFWorkbook workbook = new XSSFWorkbook(file.getInputStream());
for (int numSheet = 0; numSheet < workbook.getNumberOfSheets(); numSheet++) {
XSSFSheet sheetAt = workbook.getSheetAt(numSheet);
if (sheetAt == null) {
continue;
}
// 循环行Row
for (int rowNum = 0; rowNum <= sheetAt.getLastRowNum(); rowNum++) {
XSSFRow row = sheetAt.getRow(rowNum);
if (row == null) {
continue;
}
// 循环列Cell
for (int cellNum = 0; cellNum <= row.getLastCellNum(); cellNum++) {
//在此可进行获取单元格值并入库
getValue(row,cellNum);
}
}
}
}
//单元格类型转换并获取值
private String getValue(XSSFRow row,int cellNum) {
XSSFCell cell = row.getCell(cellNum);
if (cell.getCellType() == cell.CELL_TYPE_BOOLEAN) {
return String.valueOf(cell.getBooleanCellValue());
} else if (cell.getCellType() == cell.CELL_TYPE_NUMERIC) {
return String.valueOf((int) cell.getNumericCellValue());
} else {
return String.valueOf(cell.getStringCellValue()).equals("") ? "" : String
.valueOf(cell.getStringCellValue());
}
}
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |