@ApiOperation("导出")
@GetMapping("/batchOut")
public ResultInfo batchOut(
String ids,//如果为空就导出全部
String keyword//搜索关键字
) throws IOException, IllegalAccessException, NoSuchFieldException {
List<TDemo> resultList;
List<Integer> idList = Lists.newArrayList();
if (!StringUtils.isEmpty(ids)) {
for (String s : ids.split(",")) {
idList.add(Integer.valueOf(s));
}
}
if (idList == null || idList.size() == 0) {
//在这里构建wrapper
resultList = tDemoService.list(wrapper);
}else {
resultList = (List<TDemo>)tDemoService.listByIds(idList);
}
Integer id = FastDfsUtil.upload(new File(getSimpleBatchFile(resultList)));
FastdfsFile fastdfsFile = FastDfsUtil.selectByPrimaryKey(id);
//TODO 改为配置文件
String targetUrl = host + fastdfsFile.getFullPath();
String downloadFileName = String.format("demo类对象列表.xlsx");
HttpUtil.forward(response, targetUrl, downloadFileName);
return ResultInfo.sucess("导出成功");
}
下面是实际生成excel文件给出路径的私有方法,注意实体类的相关注解一定要写上。
通过new File(getSimpleBatchFile(dataList))拿到文件,controller层的具体下载方法可以不同。
private String getSimpleBatchFile(List<TDemo> objects) throws IOException, IllegalAccessException {
//如需去掉那些不用导出的属性,在此列表中加上,再检查字段是否需要额外处理
List<String> noNeedFields = new ArrayList<>();
noNeedFields.add("testField");
noNeedFields.add("demoStatus");
XSSFWorkbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet("demo类对象数据");
Field[] fields = TDemo.class.getDeclaredFields();
Row titleRow = sheet.createRow(0);
for (int i = 0; i < fields.length; i++) {
if (noNeedFields.contains(fields[i].getName())){
continue;
}
if (fields[i].getAnnotation(ApiModelProperty.class) == null) {
System.out.println(fields[i].getName());
continue;
}
titleRow.createCell(i).setCellValue(fields[i].getAnnotation(ApiModelProperty.class).value());
}
for (int i = 0; i < objects.size(); i++) {
Row dataRow = sheet.createRow(i + 1);
for (int j = 0; j < fields.length; j++) {
if (noNeedFields.contains(fields[j].getName())){
continue;
}
if (fields[j].getAnnotation(ApiModelProperty.class) == null) {
System.out.println(fields[j].getName());
continue;
}
fields[j].setAccessible(true);
if (fields[j].get(objects.get(i)) == null) {
dataRow.createCell(j).setCellValue("-");
continue;
}
//处理时间显示不规范的属性
if (StringUtils.contains(fields[j].getName(), "Date")) {
Date theTime = (Date) fields[j].get(objects.get(i));
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(Constants.DATE_FORMAT);
String content = simpleDateFormat.format(theTime);
dataRow.createCell(j).setCellValue(content);
continue;
}
dataRow.createCell(j).setCellValue(fields[j].get(objects.get(i)).toString());
}
}
String dateString = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
String path = String.format("/root/mytest/tempfile/%s.xlsx", dateString);
wb.write(new FileOutputStream(path));
return path;
}