项目需求:
1.下载excel模板
2.上传excel文件到指定目录
3.读取excel文件到实体类
参考资料:https://www.cnblogs.com/Crysta1/p/6002951.html
http://whoosh.iteye.com/blog/2203039
1.模板下载java代码
/**
* 导出模板
* @throws IOException
*/
@Log("导出模板")
@RequestMapping("/exportExcel")
@RequiresPermissions("kp:qualityproject:exportExcel")
public void exportExcel(HttpServletRequest request,
HttpServletResponse response) throws IOException{
String str = "D:/data/HRKP/V1.0/jeefast/jeefast-system/src/main/resources/excel-templates/templates/test.xls";
File f = new File(str);
// 设置response参数,可以打开下载页面
response.reset();
response.setContentType("application/vnd.ms-excel;charset=utf-8");
try {
response.setHeader("Content-Disposition", "attachment;filename="+ new String(("模板" + ".xls").getBytes(), "iso-8859-1"));//下载文件的名称
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
ServletOutputStream out = response.getOutputStream();
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(new FileInputStream(f));
bos = new BufferedOutputStream(out);
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
} catch (final IOException e) {
throw e;
} finally {
if (bis != null)
bis.close();
if (bos != null)
bos.close();
}
}
2.文件上传到指定目录,并读取到实体类java代码
@Log("上传文件并导入")
@RequestMapping("/upload")
@RequiresPermissions("kp:qualityproject:upload")
public String upload(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request){
String path = "D:/data/HRKP/V1.0/jeefast/jeefast-system/src/main/resources/excel-templates/templates/";
String fileName = file.getOriginalFilename();
System.out.println(path);
File targetFile = new File(path,fileName);
if(!targetFile.exists()){
//先得到文件的上级目录,并创建上级目录,再创建文件
targetFile.getParentFile().mkdir();
try {
//创建文件
targetFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
//保存
try {
file.transferTo(targetFile);
} catch (Exception e) {
e.printStackTrace();
}
//上传
try {
// 将Excel内容读至List<List<String>>对象内
String excelpath = "templates/"+fileName;
List<Object> lists = ExcelUtil.getInstance().readExcel2ObjsByPath(excelpath, HrQualitypersonalDepart.class, 0, 0);
System.out.println("读取Excel至String数组:");
for (Object list : lists) {
HrQualitypersonalDepart ls = (HrQualitypersonalDepart)list;
System.out.println(ls);
}
} catch (Exception e) {
e.printStackTrace();
}
return "result";
}
3.实体类
package cn.jeefast.kp.entity;
import java.io.Serializable;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.activ