1、添加依赖
<dependency>
<groupId>net.sf.jxlsgroupId>
<artifactId>jxls-coreartifactId>
<version>1.0.3version>
dependency>
3、代码块
@ResponseBody
@RequestMapping("/exportScience/{printData}")
public ResponseEntity<byte[]> exportScienceInfo(@PathVariable("printData") String params, HttpServletRequest request) throws Exception {
Map<String, Object> condition = JSON.parseObject(params);
String volumeType = String.valueOf(condition.get("volumeType"));
String currentUserName = String.valueOf(condition.get("currentUserName"));
String name = "";
if ("1".equals(volumeType)) {
name = "清单111";
}else{
name = "清单222";
}
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Map<String,Object> dataMap = new HashMap<>();
String path = request.getServletContext().getRealPath("/");
Configuration configuration = new Configuration();
configuration.setDefaultEncoding("utf-8");
//String srcFilePath = ServletActionContext.getServletContext().getRealPath("WEB-INF/template/aaa.xls");
//String srcFilePath = request.getServletContext().getRealPath("/finishedBorrowWaitTemplate.xls");
List<BorrowTaskDto> list = borrowTaskService.getScienceInfo(condition);
Map<String, List<BorrowTaskDto>> groupListMap = list.stream().collect(Collectors.groupingBy(BorrowTaskDto::getApplyUid));
Set<String> keySet = groupListMap.keySet();
int num = 1;
for (String k : keySet) {
//List tempList = groupListMap.get(k).stream().sorted((o1, o2) -> o2.getCreateTime().compareTo(o1.getCreateTime())).collect(Collectors.toList());
List<BorrowTaskDto> tempList = groupListMap.get(k);
for (int i = 0; i < tempList.size(); i++) {
tempList.get(i).setNumber(i + 1);
tempList.get(i).setApplyTimeStr(dateFormat.format(tempList.get(i).getApplyTime()));
}
UserDto printUser = new UserDto();
printUser.setUserNo(tempList.get(0).getUserNo());
printUser.setUserName(tempList.get(0).getApplyName());
printUser.setOrgName(tempList.get(0).getOrgName());
printUser.setCellphone(tempList.get(0).getUserCellPhone());
printUser.setAddress(tempList.get(0).getUserAddress());
dataMap.put("user"+num,printUser);
dataMap.put("list"+num,tempList);
dataMap.put("num",num);
num++;
}
File sfile = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + "template/borrowChecklist/checkList10.xls");
//File sfile = ResourceUtils.getFile("D:\\program\\jaf\\src\\main\\resources\\template\\borrowChecklist\\checkList10.xls");
String srcFilePath = sfile.getAbsolutePath();
// 公共部分
dataMap.put("admin",currentUserName);
dataMap.put("date", dateFormat.format(new Date()));
XLSTransformer transformer = new XLSTransformer();
File exportFile = new File(String.format("%s%s.%s",path,name,"xls"));//File.createTempFile(String.format("%s%s",path,name), ".xls");
transformer.transformXLS(srcFilePath, dataMap, exportFile.getAbsolutePath());
String filename = String.format("%s.%s",name,"xls");
File file = new File(path+filename);
HttpHeaders headers = new HttpHeaders();
//下载显示的文件名,解决中文名称乱码问题
String downloadFileName = new String(filename.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
//通知浏览器以attachment(下载方式)打开图片
headers.setContentDispositionFormData("attachment", downloadFileName);
//application/octet-stream:二进制流数据(最常见的文件下载)
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
//201 HttpStatus.CREATED
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.CREATED);
}
导出结果:
本次导出的excel中和模板一样,一共有10个sheet,有数据的sheet1 和sheet2, 其余的sheet3到sheet10没数据留白
以上存在两个待优化项:
1、模板里面需要建固定个sheet(需要打10个,所以要10个sheet)不是动态的
2、在Linux上打出会报错,报取不到模板文件的错误
优化:
1、模板优化:sheet个数不在固定,可以动态生成
2、在Linux也可以找到模板文件
代码
@ResponseBody
@RequestMapping("/exportScience/{printData}")
public void exportScienceInfo(@PathVariable("printData") String params, HttpServletRequest request,HttpServletResponse response) throws Exception {
Map<String, Object> condition = JSON.parseObject(params);
String volumeType = String.valueOf(condition.get("volumeType"));
String currentUserName = String.valueOf(condition.get("currentUserName"));
String name = "";
if ("1".equals(volumeType)) {
name = "清单111.xls";
}else{
name = "清单222.xls";
}
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String path = request.getServletContext().getRealPath("/");
Configuration configuration = new Configuration();
configuration.setDefaultEncoding("utf-8");
List<BorrowTaskDto> list = borrowTaskService.getScienceInfo(condition);
Map<String, List<BorrowTaskDto>> groupListMap = list.stream().collect(Collectors.groupingBy(BorrowTaskDto::getApplyUid));
Set<String> keySet = groupListMap.keySet();
ArrayList<Map<String,Object>> objects = new ArrayList<>();
List<String> sheetNameList = new ArrayList<String>();
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("admin",currentUserName);
map.put("date", dateFormat.format(new Date()));
int num = 0;
for (String k : keySet) {
List<BorrowTaskDto> tempList = groupListMap.get(k);
for (int i = 0; i < tempList.size(); i++) {
tempList.get(i).setNumber(i + 1);
tempList.get(i).setApplyTimeStr(dateFormat.format(tempList.get(i).getApplyTime()));
}
UserDto printUser = new UserDto();
printUser.setUserNo(tempList.get(0).getUserNo());
printUser.setUserName(tempList.get(0).getApplyName());
printUser.setOrgName(tempList.get(0).getOrgName());
printUser.setCellphone(tempList.get(0).getUserCellPhone());
printUser.setAddress(tempList.get(0).getUserAddress());
Map<String,Object> dataMap = new HashMap<>();
sheetNameList.add(tempList.get(0).getApplyName());// sheet的名称
dataMap.put("user",printUser);
dataMap.put("subList",tempList);
objects.add(dataMap);
map.put("list"+num,tempList );
num++;
}
ClassPathResource classPathResource = new ClassPathResource("template/borrowChecklist/checkList10.xls");
//File sfile = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + "template/borrowChecklist/checkList10.xls");
//FileInputStream fis = new FileInputStream(sfile);;
//这种方式 在linux下可以找到模板文件流
InputStream inputStream = classPathResource.getInputStream();
OutputStream outputStream=new FileOutputStream(String.format("%s%s.%s",path,"checkList10","xls"));
int b=0;
while((b=inputStream.read())!=-1){
outputStream.write(b);
}
inputStream.close();
outputStream.close();
//FileInputStream fis = new FileInputStream(classPathResource.getFile());;
FileInputStream fis = new FileInputStream(String.format("%s%s.%s", path, "checkList10", "xls"));
OutputStream out = null;
String contentType = "application/vnd.ms-excel";
response.setContentType(contentType);
String downloadFileName = new String(name.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
response.setHeader("Content-Disposition", "attachment;filename=" + downloadFileName);
response.setHeader("Pragma", "public");
response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
response.setHeader("Cache-Control", "public");
response.setHeader("Expires", "0");
response.setHeader("Content-Transfer-Encoding", "binary");
XLSTransformer transformer = new XLSTransformer();
// 这里的list,是map中存放的list
Workbook workbook = transformer.transformMultipleSheetsList(fis, objects, sheetNameList, "list", map, 0);
out = response.getOutputStream();
workbook.write(out);
out.flush();
out.close();
}