说明:
上传multipartFile时,无法直接转为File去读取excel文件内容,因为为了安全,不可能知道客户端文件绝对路径,解决方法为在服务器端生成一个File文件,然后再读取这个服务器的文件内容保存到数据库
controller
/**
* 导入
* @param id
* @return
*/
@RequestMapping(value = "/uploadCustList",method = RequestMethod.POST)
@ResponseBody
public ResultModel uploadCustList(@RequestParam String flag, String masterDate, @RequestParam MultipartFile[] myfiles, HttpServletRequest request) {
log.info(this.getClass().getName()+".uploadCustList.start");
ResultModel result=new ResultModel();
StringBuffer buffer=new StringBuffer();
String originalFilename="";//上传的文件的文件名
String suffix="";
//校验上传文件上否为空
if(null==myfiles || myfiles.length<=0){
result.setResultMsg(Constants.SERVICE_ERROR_CODE);
result.setResultMsg(Constants.FILE_NULL_ERROR);
return result;
}
for (MultipartFile myfile : myfiles) {
if (!myfile.isEmpty()) {
//获得文件后缀名
suffix = myfile.getOriginalFilename().substring(myfile.getOriginalFilename().lastIndexOf("."));
//获得文件源名
originalFilename=myfile.getOriginalFilename();
log.info(this.getClass().getName()+".uploadCustList.originalFilename="+originalFilename);
//强转为File
String path=request.getSession().getServletContext().getRealPath("/upload/");
suffix = myfile.getOriginalFilename().substring(myfile.getOriginalFilename().lastIndexOf("."));
String fileName = UUID.randomUUID().toString()+ suffix;
File f=new File(path,fileName);
try {
myfile.transferTo(f);
Map<String,Object> map=custemerListService.saveExcelAndConverToText(f);
} catch (IllegalStateException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//检查文件格式
if(null!=buffer && buffer.length()>0){
result.setResultMsg(Constants.SERVICE_ERROR_CODE);
result.setResultMsg(buffer.toString());
return result;
}
return result;
}
service
/**
* 读取excel文件内容保存到数据库,并将文件转为txt格式发送到sftp
*/
@Override
public Map<String, Object> saveExcelAndConverToText(File file) {
Map<String,Object> resultMap=new HashMap<String,Object>();
//获取excel文件
XSSFWorkbook xssfWorkbook;
try {
xssfWorkbook = new XSSFWorkbook(new FileInputStream(file));
for (int numSheet = 0; numSheet < xssfWorkbook.getNumberOfSheets(); numSheet++) {
XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(numSheet);
if (xssfSheet == null) {
continue;
}
// Read the Row
for (int rowNum = 1; rowNum <= xssfSheet.getLastRowNum(); rowNum++) {
XSSFRow xssfRow = xssfSheet.getRow(rowNum);
if (xssfRow != null) {
//student = new Student();
XSSFCell no = xssfRow.getCell(0);
XSSFCell name = xssfRow.getCell(1);
XSSFCell age = xssfRow.getCell(2);
XSSFCell score = xssfRow.getCell(3);
// student.setNo(getValue(no));
// student.setName(getValue(name));
// student.setAge(getValue(age));
// student.setScore(Float.valueOf(getValue(score)));
// list.add(student);
}
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//转换文件格式
// converToText(file);
//读取文件内容保存到数据库
//readExcel();
//发送文件到sftp
//sendToSFTP();
return resultMap;
}