controller如下:
/**
* 导入值班表*
* @param dutyExcel
* @return String(导入结果描述)
*/
@RequestMapping(value = "importDutyExcel")
@ResponseBody
public String importDutyExcel(@RequestParam(value = "dutyExcel", required = false) MultipartFile dutyExcel) {
System.out.println("进入");
// 1、获取excel文件
String rString = "";
if (dutyExcel != null) {
String fileName = dutyExcel.getOriginalFilename();
// 判断是否是excel
if (fileName.matches("^.+\\.(?i)((xls)|(xlsx))$")) {
rString = excelService.importDutyExcel(dutyExcel);
System.out.println(rString);
}
}
return "success";
}
service如下:
//如下为文件不能加密的解决方案以及注释掉的加密解决方案
/**
* 获取的Excel文件中可操作的sheet
*
* @param dutyExcel
* @return sheet
* @throws Exception
*/
private Sheet getSheetOfExcel(MultipartFile dutyExcel) throws Exception {
Sheet sheet = null;
try {
// 版本判断
boolean is03Excel = dutyExcel.getOriginalFilename().matches("^.+\\.(?i)(xls)$");
// 后缀
String postfix = is03Excel ? ".xls" : ".xlsx";
/*
* 文件加密方式下解决策略
* // 将上传生成的临时文件写入到本地新建的文件中
* CommonsMultipartFile cf = (CommonsMultipartFile) dutyExcel;
* File file = new File("D:\\fileupload");
* // 创建一个目录 (它的路径名由当前 File 对象指定,包括任一必须的父路径。)
* if (!file.exists())
* file.mkdirs();
* // 新建一个文件
* temExeclFile = new File("D:\\fileupload\\" + new Date().getTime()
* + postfix);
* // 将上传的文件写入新建的文件中
* try {
* cf.getFileItem().write(temExeclFile);
* } catch (Exception e) {
* e.printStackTrace();
* }
* System.out.println("开始睡眠");
* Thread.sleep(4000);
* System.out.println("结束睡眠");
* // 写入输入流
* fileInputStream = new FileInputStream(temExeclFile);
*
* System.out.println(fileInputStream.getFD());
*/
// 1、读取工作簿
Thread.sleep(1000);
Workbook workbook = getWorkbook(is03Excel, dutyExcel.getInputStream());
// 2、读取工作表
sheet = workbook.getSheetAt(0);
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
return sheet;
}
// 根据excel版本获取workbook
private Workbook getWorkbook(Boolean is03Excel, InputStream InputStream) throws IOException {
Workbook workbook = null;
if (is03Excel) {
workbook = new HSSFWorkbook(InputStream);
} else {
System.out.println(InputStream.toString());
workbook = new XSSFWorkbook(InputStream);
}
return workbook;
}