Spring boot框架根据模板实现文件导出功能
文件导出:
service层代码:
@Override
public BaseResponse<List<Map<String, String>>> export(List<Long> ids) {
List<CorpPersonSum> corpPersonSums = getProList(ids);
if(org.apache.dubbo.common.utils.CollectionUtils.isEmpty(corpPersonSums)){
return BaseResponse.buildSuccessResponse();
}
ArrayList<Map<String, String>> response = Lists.newArrayList();
Map<String,String> levelOneConstructor = dictionaryService.queryValueAndTextMap(String.valueOf(CorpPersonEnum.LEVEL_ONE_CONSTRUCTOR));
Map<String,String> levelTwoConstructor = dictionaryService.queryValueAndTextMap(String.valueOf(CorpPersonEnum.LEVEL_TWO_CONSTRUCTOR));
Map<String,String> registeredEngineer = dictionaryService.queryValueAndTextMap(String.valueOf(CorpPersonEnum.REGISTERED_CONSULTANT_ENGINEER));
for (int i = 1; i <= corpPersonSums.size(); i++) {
CorpPersonSum corpPersonSum = corpPersonSums.get(i - 1);
HashMap<String, String> result = Maps.newHashMap();
result.put("0", String.valueOf(i));
//corpBaseInfoService.getProjectNameById(corpPersonSum.getCorpId());
CorpPersonSumPageRespDTO corpPersonSumPageRespDTO = new CorpPersonSumPageRespDTO();
result.put("1", Optional.ofNullable(corpBaseInfoService.getcorpNameById(corpPersonSum.getCorpId())).orElse(""));
result.put("2", String.valueOf(Optional.ofNullable(corpPersonSum.getTotalStaff()).orElse(Integer.valueOf(""))));
result.put("3",levelOneConstructor.getOrDefault(corpPersonSumPageRespDTO.getLevelOneConstructor(),""));
result.put("4",levelTwoConstructor.getOrDefault(corpPersonSumPageRespDTO.getLevelTwoConstructor(),""));
result.put("5",registeredEngineer.getOrDefault(corpPersonSumPageRespDTO.getRegisteredEngineer(),""));
result.put("6",String.valueOf(Optional.ofNullable(corpPersonSum.getProfessorEngineer()).orElse(Integer.valueOf(""))));
result.put("7",String.valueOf(Optional.ofNullable(corpPersonSum.getHighGradeEngineer()).orElse(Integer.valueOf(""))));
result.put("8",String.valueOf(Optional.ofNullable(corpPersonSum.getMiddleGradeEngineer()).orElse(Integer.valueOf(""))));
result.put("9",String.valueOf(Optional.ofNullable(corpPersonSum.getTechnician()).orElse(Integer.valueOf(""))));
result.put("10",String.valueOf(Optional.ofNullable(corpPersonSum.getAdministrativeStaff()).orElse(Integer.valueOf(""))));
result.put("11",String.valueOf(Optional.ofNullable(corpPersonSum.getOnsiteManageStaff()).orElse(Integer.valueOf(""))));
result.put("12",String.valueOf(Optional.ofNullable(corpPersonSum.getOtherStaff()).orElse(Integer.valueOf(""))));
response.add(result);
}
return BaseResponse.buildSuccessResponse().result(response);
}
controller层代码:
@RequestMapping("/export")
public void export(String ids) {
if(StringUtils.isEmpty(ids)) {
log.info("参数不正确");
return;
}
List<Long> collect = CommonUtil.parseString(ids);
String businessModule = BusinessModuleEnum.CORP_PERSON_INFO.getBusinessType();
String businessType = BusinessTypeEnum.CORP_PERSON_INFO_EXCEL.getCode();
BaseResponse<FileRespDTO> fileInfoResponse = fileTemplateRSV.getFileInfo(businessModule, businessType);
FileRespDTO fileData = RemoteInvocationUtil.getResult(fileInfoResponse);
if (Objects.isNull(fileData) || StringUtils.isBlank(fileData.getFileUrl())) {
log.info("文件模板不存在,businessModule:{}, businessType:{}", businessModule, businessType);
return;
}
String url = fileData.getFileUrl();
byte[] result = RemoteInvocationUtil.getResult(fileCommonRSV.download(url));
if (result != null && result.length != 0) {
BaseResponse<List<Map<String, String>>> exportResponse = corpPersonSumRSV.export(collect);
if(ObjectUtils.isNotEmpty(exportResponse) && exportResponse.getSuccess()) {
String fileName = "列表";
ExcelUtils.exportExcel(BusinessTypeEnum.CORP_PERSON_INFO_EXCEL, fileName,
"Sheet1", result, exportResponse.getResult(), null, resp);
}
}
}
对应的枚举类型:
CORP_PERSON_INFO_EXCEL("corp_base_info_excel","excel导出模板"),
CORP_PERSON_INFO("corp_person_info","corpPersonInfo", "", null, null,
"人员信息"),
**文件下载:**
controller层代码:
@RequestMapping("/init")
@ApiOperation(tags = "模板下载", value = "模板下载", httpMethod = "POST")
public BaseResponseVO<JSONObject> init(){
HmExcellentProjectFormEntity hmExcellentProjectFormEntity = new HmExcellentProjectFormEntity();
JSONObject formDefinition = formilyEngineService.getFormilyJsonWithValue(hmExcellentProjectFormEntity, null, null);;
if (Objects.nonNull(formDefinition)) {
SafetyDTO safetyDTO = new SafetyDTO();
safetyDTO.setId(null);
safetyDTO.setBusinessId(null);
safetyDTO.setBusinessModule(BusinessModuleEnum.SPONGE_AWARD.name());
JSONObject jsonObject = new JSONObject(true);
jsonObject.put("schema", formDefinition);
jsonObject.put("params", JSONObject.parseObject(JSONObject.toJSONString(safetyDTO)));
return BaseResponseVO.success(jsonObject);
}
return BaseResponseVO.error("失败");
}
}
@GetMapping("/download")
public void download(String templateBusinessModule, String templateBusinessType) {
ServletOutputStream sos = null;
try {
//1.获取pdfkey
BaseResponse<FileRespDTO> fileInfoResponse = FileTemplateRSV.getFileInfo(templateBusinessModule, templateBusinessType);
if (null == fileInfoResponse || (null != fileInfoResponse && fileInfoResponse.getSuccess() == false)) {
return;
}
FileRespDTO data = fileInfoResponse.getResult();
if (null == data) {
return;
}
if (StringUtils.isBlank(data.getFileUrl())) {
return;
}
byte[] result = RemoteInvocationUtil.getResult(fileCommonRSV.download(data.getFileUrl()));
if (result != null && result.length != 0) {
sos = resp.getOutputStream();
resp.setContentType(String.format("%s;charset=UTF-8", data.getType()));
String filename = new String(data.getFileName().getBytes(), "ISO-8859-1");
resp.addHeader("Content-Disposition", String.format("attachment;filename=%s", filename));
sos.write(result);
sos.flush();
}
} catch (IOException e) {
log.error("发生异常===={}", e.getMessage(), e);
} finally {
try {
if (null != sos) {
sos.close();
}
} catch (IOException e) {
log.error("发生异常===={}", e.getMessage(), e);
}
}
}
service层代码:
@Override
public BaseResponse<FileRespDTO> getFileInfo(String businessModule, String businessType) {
if (StringUtils.isBlank(businessModule) || StringUtils.isBlank(businessType)) {
return BaseResponse.buildErrorResponse().code(CommonError.Code.PARAM_NOT_NULL.getCode());
}
Long fileId = yjFileTemplateRelaService.getFileId(businessModule, businessType);
FileRespDTO yjFile = yjFileService.getFileInfoById(fileId);
return BaseResponse.buildSuccessResponse().result(yjFile);
}
@Override
public Long getFileId(String businessModule, String businessType) {
if (StringUtils.isBlank(businessModule) || StringUtils.isBlank(businessType)) {
return null;
}
FileTemplateRelaExample example = new FileTemplateRelaExample();
FileTemplateRelaExample.Criteria criteria = example.createCriteria();
criteria.andBusinessModuleEqualTo(businessModule);
criteria.andBusinessTypeEqualTo(businessType);
Optional<Collection<FileTemplateRela>> result = this.queryByExample(example);
List<FileTemplateRela> fileTemplateRelas = (List<FileTemplateRela>) result.orElse(null);
if (CollectionUtils.isEmpty(fileTemplateRelas) || ObjectUtils.isEmpty(fileTemplateRelas.get(0))) {
return null;
}
return fileTemplateRelas.get(0).getFileId();
}
@Override
public FileRespDTO getFileInfoById(Long id) {
if (ObjectUtils.isEmpty(id)) {
return null;
}
FileExample example = new FileExample();
example.createCriteria().andDeletedEqualTo(CommonConstants.UN_DELETED).andIdEqualTo(id);
Optional<File> File = this.queryOneByExample(example);
if (!File.isPresent()) {
return null;
}
return convertFileRespVo(File.get(), null);
}
对应文件DTO:
@Data
@ApiModel(value = "FileRespDTO", description = "附件信息DTO")
public class FileRespDTO implements Serializable {
/**
* 文件名
*/
@ApiModelProperty(name = "fileName", value = "文件名")
private String fileName;
/**
* 文件唯一key
*/
@ApiModelProperty(name = "key", value = "文件唯一key")
private String key;
/**
* 文件转pdf的
*/
@ApiModelProperty(name = "pdfKey", value = "文件转pdf的")
private String pdfKey;
/**
* 文件url
*/
@ApiModelProperty(name = "fileUrl", value = "文件url")
private String fileUrl;
/**
* pdf文件url
*/
@ApiModelProperty(name = "pdfFileUrl", value = "文件转pdf后url")
private String pdfFileUrl;
/**
* 文件类型
*/
@ApiModelProperty(name = "type", value = "文件类型")
private String type;
/**
* 文件内容
*/
@ApiModelProperty(name = "fileData", value = "文件内容byte数组")
private byte[] fileData;
/**
* 文件内容
*/
@ApiModelProperty(name = "fileData", value = "文件内容base64")
private String base64Data;
/**
* 文件后缀
*/
@ApiModelProperty(name = "subbfix", value = "文件后缀")
private String subbfix;
/**
* 业务模块
*/
@ApiModelProperty(name = "businessModule", value = "业务模块")
private String businessModule;
/**
* 业务类型
*/
@ApiModelProperty(name = "businessType", value = "业务类型")
private String businessType;
@ApiModelProperty(name = "businessId", value = "业务id")
private Long businessId;
@ApiModelProperty(name = "gmtCreate", value = "上传时间")
private Date gmtCreate;
@ApiModelProperty(name = "gmtCreateStr", value = "上传时间")
private String gmtCreateStr;
@ApiModelProperty(name = "creator", value = "上传人")
private Long creator;
@ApiModelProperty(name = "creatorName", value = "上传人姓名")
private String creatorName;
@ApiModelProperty(name = "fileId", value = "文件id")
private Long fileId;
@ApiModelProperty(name = "fileType", value = "文件类型")
private int fileType;
}
版权声明:本文为qq_42793254原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。