创建一个docx的word文档,编辑好模板,比如trip.docx。
trip.docx另存为trip.xml
格式化trip.xml(方便阅读和替换里面的变量)
替换变量,更改为trip.ftl放入项目中
java代码填充数据,并保存word
引入jar
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.28</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.7</version>
</dependency>
Controller
package com.sjasoft.cloud.admin.controller.ems;
import com.sjasoft.cloud.admin.dto.ems.ExprotWordParam;
import com.sjasoft.cloud.admin.service.ems.ExportWordService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
/**
* 导出word文档接口
* @version 1.0
* @date 2021/3/16 15:57
*/
@Controller
@RequestMapping("/ems/exportWord")
@Api(tags = "ExportWordController", description = "导出word文档接口")
public class ExportWordController {
@Autowired
private ExportWordService exportWordService;
@ResponseBody
@PostMapping(value = "/exportTotalReportWord")
@ApiOperation(value = "导出报告")
public void exportTotalReportWord(HttpServletResponse response, @RequestBody ExprotWordParam exprotWordParam) {
exportWordService.exportTotalReportWord(response,exprotWordParam);
}
}
Service
package com.sjasoft.cloud.admin.service.ems;
import com.sjasoft.cloud.admin.dao.ems.DeploymentPlanDao;
import com.sjasoft.cloud.admin.dao.ems.ExportWordDao;
import com.sjasoft.cloud.admin.dto.ems.*;
import com.sjasoft.cloud.admin.dto.emsapp.EmsProjectDropDownInfoVo;
import com.sjasoft.cloud.admin.service.emsapp.ProjectImageAppService;
import com.sjasoft.cloud.admin.service.emsapp.ProjectInfoService;
import com.sjasoft.cloud.admin.utils.ExportWordUtils;
import com.sjasoft.framework.common.utils.DateUtil;
import com.sjasoft.framework.common.utils.StringUtil;
import com.sjasoft.mbg.ems.model.EmsDeploymentPlan;
import com.sjasoft.mbg.ems.model.EmsResourceGroup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
/**
* @Author lufei
* @Description 导出wordService
* @Date 下午 04:29 2021/3/15
**/
@Service
public class ExportWordService {
private static Logger logger = LoggerFactory.getLogger(ExportWordService.class);
@Resource
private ExportWordDao exportWordDao;
@Resource
private MinIoService minIoService;
@Resource
private DeploymentPlanDao deploymentPlanDao;
@Resource
private ProjectImageAppService projectImageAppService;
@Resource
private ProjectInfoService projectInfoService;
@Resource
private ExportHistoryService exportHistoryService;
/**
* 查询勘探现场图片,以及安装现场图片
* @param projectKeyId 项目id
* @return 设备列表
*/
public List<EmsDeploymentPlan> explorOrInsList(@NotNull String projectKeyId) {
List<EmsDeploymentPlan> getDeploymentPhoto = deploymentPlanDao.getDeploymentPhoto(projectKeyId);
for (int i = 0;i < getDeploymentPhoto.size();i++){
//学校门头
if (!StringUtil.isNullOrEmpty(getDeploymentPhoto.get(i).getSchoolPhoto())){
getDeploymentPhoto.get(i).setSchoolPhoto(projectImageAppService.downloadProjectPhoto(getDeploymentPhoto.get(i).getSchoolPhoto()));
}
//学校场景一
if (!StringUtil.isNullOrEmpty(getDeploymentPhoto.get(i).getScenePhotoOne())){
getDeploymentPhoto.get(i).setScenePhotoOne(projectImageAppService.downloadProjectPhoto(getDeploymentPhoto.get(i).getScenePhotoOne()));
}
//环境设备的位置
if (!StringUtil.isNullOrEmpty(getDeploymentPhoto.get(i).getEnvironmentalPosition())){
getDeploymentPhoto.get(i).setEnvironmentalPosition( projectImageAppService.downloadProjectPhoto(getDeploymentPhoto.get(i).getEnvironmentalPosition()));
}
//安全设备的位置
if (!StringUtil.isNullOrEmpty(getDeploymentPhoto.get(i).getSecurityPosition())){
getDeploymentPhoto.get(i).setSecurityPosition(projectImageAppService.downloadProjectPhoto(getDeploymentPhoto.get(i).getSecurityPosition()));
}
//学校场景二
if (!StringUtil.isNullOrEmpty(getDeploymentPhoto.get(i).getScenePhotoTwo())){
getDeploymentPhoto.get(i).setScenePhotoTwo(projectImageAppService.downloadProjectPhoto(getDeploymentPhoto.get(i).getScenePhotoTwo()));
}
}
return getDeploymentPhoto;
}
/**
* 根据项目ID获取安全报警示例图
* @param projectKeyId 项目keyId
* @return
*/
public List<ExportWordAlermImageVo> getSafeAlarmExamImage(String projectKeyId){
List<ExportWordAlermImageVo> alermImageVoList = new ArrayList<>();
try {
//查询资源组信息
List<EmsResourceGroup> resourceGroupList = exportWordDao.getEmsResourceGroupList(projectKeyId);
if(CollectionUtils.isEmpty(resourceGroupList) || StringUtil.isNullOrEmpty(projectKeyId)){
return alermImageVoList;
}else {
//小图个数
int countMin = 0;
int countMax = 0;
ExportWordAlermImageVo wordAlermImageVo;
for(EmsResourceGroup resourceGroup : resourceGroupList){
//父ID为空是大图
wordAlermImageVo = new ExportWordAlermImageVo();
if(StringUtil.isNullOrEmpty(resourceGroup.getPid())){
if(countMax > 1){
continue;
}
if(!StringUtil.isNullOrEmpty(resourceGroup.getContent())){
wordAlermImageVo.setAlermMaxImageNo("maxImage" + countMax);
wordAlermImageVo.setAlermMaxImageBase64(minIoService.downloadPhotoBase64(resourceGroup.getContent()));
countMax ++;
}
}else {
if(countMin > 1){
continue;
}
if(!StringUtil.isNullOrEmpty(resourceGroup.getContent())){
wordAlermImageVo.setAlermMinImageNo("minImage" + countMin);
wordAlermImageVo.setAlermMinImageBase64(minIoService.downloadPhotoBase64(resourceGroup.getContent()));
countMin ++;
}
}
alermImageVoList.add(wordAlermImageVo);
if(countMin == 2 && countMax == 2){
//组合2组图片跳出
break;
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
return alermImageVoList;
}
/**
* 根据ID获取环境报警阈值
* @param projectKeyId
* @return sampleName 采样名称 compareName 比较单位 compareValue 比较值 unit 计量单位
*/
public List<EnvAlarmThresholdVo> getEnvAlarmThreshold(String projectKeyId){
List<EnvAlarmThresholdVo> thresholdVoList = exportWordDao.getEnvAlarmThreshold(projectKeyId);
return thresholdVoList;
}
/**
* 根据项目ID获取项目信息(项目基本信息,项目总体情况,项目每日报警统计List,项目环境报警统计List)
* @param projectId
* @return
*/
public Map<String,Object> getProjectInformationByProjectId(String projectId){
/*if(StringUtil.isNullOrEmpty(projectId)){
return Result.failure("项目ID不能为空");
}*/
Map<String,Object> projectInformationMap = new HashMap();
//项目基本信息
ProjectBasicInformation projectBasicInformation = exportWordDao.getProjectBasicInformationByProjectId(projectId);
if(projectBasicInformation != null){
List<InstallationEquipmentInformation> installationEquipmentList = new ArrayList<>();
//录像机 DS-7604NB-K1 1
InstallationEquipmentInformation videorecorder = new InstallationEquipmentInformation();
videorecorder.setDeviceType("录像机");
videorecorder.setDeviceModel("DS-7604NB-K1");
videorecorder.setDeviceNumber(1);
installationEquipmentList.add(videorecorder);
//摄像头 DS-2CD2T25F-I3S 1
InstallationEquipmentInformation camera = new InstallationEquipmentInformation();
camera.setDeviceType("摄像头");
camera.setDeviceModel("DS-2CD2T25F-I3S");
camera.setDeviceNumber(1);
installationEquipmentList.add(camera);
//交换机(飞鱼模块) VEC210GP 1
InstallationEquipmentInformation Switch = new InstallationEquipmentInformation();
Switch.setDeviceType("交换机(飞鱼模块)");
Switch.setDeviceModel("VEC210GP");
Switch.setDeviceNumber(1);
installationEquipmentList.add(Switch);
//主机 OptiPlex 7070 Micro 1
InstallationEquipmentInformation host = new InstallationEquipmentInformation();
host.setDeviceType("主机");
host.setDeviceModel("OptiPlex 7070 Micro");
host.setDeviceNumber(1);
installationEquipmentList.add(host);
//4G路由 USER-G805-WF 1
InstallationEquipmentInformation routing4G = new InstallationEquipmentInformation();
routing4G.setDeviceType("4G路由");
routing4G.setDeviceModel("USER-G805-WF");
routing4G.setDeviceNumber(1);
installationEquipmentList.add(routing4G);
//环境监测 PM2.5、PM10、TSP、噪音、温度、湿度、气压、风速、风向、风力 1
InstallationEquipmentInformation environmentalMonitoring = new InstallationEquipmentInformation();
environmentalMonitoring.setDeviceType("环境监测");
environmentalMonitoring.setDeviceModel("PM2.5、PM10、TSP、噪音、温度、湿度、气压、风速、风向、风力");
environmentalMonitoring.setDeviceNumber(1);
installationEquipmentList.add(environmentalMonitoring);
projectBasicInformation.setInstallationEquipmentList(installationEquipmentList);
}
//项目总体情况
ProjectGeneralSituation projectGeneralSituation = exportWordDao.getProjectGeneralSituationByProjectId(projectId);
//项目每日报警统计List
List<ProjectEveryDayAlertStatistics> projectEveryDayAlertStatisticsList = exportWordDao.getProjectEveryDayAlertStatisticsListByProjectId(projectId);
//项目环境报警统计List
List<ProjectEnvironmentalAlertStatistics> projectEnvironmentalAlertStatistics = exportWordDao.getProjectEnvironmentalAlertStatisticsListByProjectId(projectId);
if(projectEnvironmentalAlertStatistics.size() > 0 && projectEnvironmentalAlertStatistics.size() !=24){
List<ProjectEnvironmentalAlertStatistics> projectEnvironmentalAlertStatisticsList = new ArrayList<>();
for(int i = 0; i <=23 ; i++){
ProjectEnvironmentalAlertStatistics p = new ProjectEnvironmentalAlertStatistics();
p.setAlertTime(i);
projectEnvironmentalAlertStatisticsList.add(p);
}
for(int i = 0 ; i < projectEnvironmentalAlertStatistics.size() ; i++){
projectEnvironmentalAlertStatisticsList.set(projectEnvironmentalAlertStatistics.get(i).getAlertTime(),projectEnvironmentalAlertStatistics.get(i));
}
projectEnvironmentalAlertStatistics=projectEnvironmentalAlertStatisticsList;
}
projectInformationMap.put("projectBasicInformation",projectBasicInformation);
projectInformationMap.put("projectGeneralSituation",projectGeneralSituation);
projectInformationMap.put("projectEveryDayAlertStatisticsList",projectEveryDayAlertStatisticsList);
projectInformationMap.put("projectEnvironmentalAlertStatistics",projectEnvironmentalAlertStatistics);
return projectInformationMap;
}
/**
* @Description 导出总计报告
* @Date 下午 03:36 2021/3/16
**/
public void exportTotalReportWord(HttpServletResponse response,ExprotWordParam exprotWordParam){
try {
List<EmsProjectDropDownInfoVo> projectInfo = new ArrayList<>();
//查询所有项目信息
if(exprotWordParam != null && CollectionUtils.isEmpty(exprotWordParam.getProjectIdList())){
projectInfo = projectInfoService.getAllProjectInfo();
}else {
projectInfo = projectInfoService.getAllProjectInfo()
.stream()
.filter(EmsProjectDropDownInfoVo -> exprotWordParam.getProjectIdList()
.contains(EmsProjectDropDownInfoVo.getProjectKeyId()))
.collect(Collectors.toList());
}
if(CollectionUtils.isEmpty(projectInfo)){
return;
}
logger.info("项目个数:{}",projectInfo.size());
//获得基础原数据
Map<String, Object> map = new HashMap<String, Object>();
map = getPrefaceInfo(map);
//存放项目信息
map.put("projectInfoList",getCatalogInfo(projectInfo));
logger.info("数据加载完毕,开始导出》》》》》》》》》》》");
// 设置浏览器以下载的方式处理该文件名
String fileName = "智慧校园总计报告".concat(DateUtil.format(new Date(), DateUtil.DATE_FORMAT_YMD_HMS)).concat(".doc");
MultipartFile multipartFile = ExportWordUtils.exportMillCertificateWord(response,map,fileName
,"simpleFTL.ftl");
if(multipartFile != null){
//添加上传历史
ExportHistoryQueryFilter exportHistoryQueryFilter = new ExportHistoryQueryFilter();
exportHistoryQueryFilter.setMultipartFile(multipartFile);
exportHistoryQueryFilter.setFileName(fileName);
exportHistoryService.create(exportHistoryQueryFilter);
logger.info("=========已添加至上传历史==========");
}
}catch (IOException e){
e.printStackTrace();
}
}
/**
* 获取前言信息
* @param map 基础原数据
* @return
*/
private Map<String, Object> getPrefaceInfo(Map<String, Object> map){
Calendar calendar = Calendar.getInstance();
//获取当前年
String nowYear = String.valueOf(calendar.get(Calendar.YEAR));
String fistTwoYear = nowYear.substring(0,2);
String lastTwoYear = nowYear.substring(nowYear.length() - 2,nowYear.length());
//获取当前月
String nowMonth = String.valueOf(calendar.get(Calendar.MONTH) + 1);
//获取当前日
String nowDay = String.valueOf(calendar.get(Calendar.DAY_OF_MONTH));
String fistTwoDay = "";
String lastTwoDay = "";
if(nowDay.length() > 1){
fistTwoDay = nowDay.substring(0,1);
lastTwoDay = nowDay.substring(1);
}else {
fistTwoDay = nowDay;
}
map.put("nowYear",nowYear);
map.put("fistTwoYear",fistTwoYear);
map.put("lastTwoYear",lastTwoYear);
map.put("nowMonth",nowMonth);
map.put("fistTwoDay",fistTwoDay);
map.put("lastTwoDay",lastTwoDay);
logger.info("前言信息已加载》》》》》");
return map;
}
/**
* 获取项目信息
* @param projectInfo
* @return
*/
private List<Map<String,Object>> getCatalogInfo( List<EmsProjectDropDownInfoVo> projectInfo){
List<Map<String,Object>> listMapCatalog = new ArrayList<>();
Map<String,Object> mapHashMap = null;
Map<String,Object> proDetailMap = null;
if(!CollectionUtils.isEmpty(projectInfo)){
BigDecimal proNo = new BigDecimal(1);
//记录柱状图、曲线图、图片等编号【仅限从1开累加1】
BigDecimal recordNum = new BigDecimal(1);
for (EmsProjectDropDownInfoVo proInfo : projectInfo){
mapHashMap = new HashMap<>();
//根据项目ID获取项目信息
proDetailMap = getProjectInformationByProjectId(proInfo.getProjectKeyId());
if(proDetailMap != null){
//项目基本信息
ProjectBasicInformation projectBasicInformation = (ProjectBasicInformation) proDetailMap.get("projectBasicInformation");
if(projectBasicInformation != null){
//监控期间
mapHashMap.put("duringMonitor", projectBasicInformation.getActualDeploymentTime() + " 到 "
+ projectBasicInformation.getActualDismantleTime());
//施工项目
mapHashMap.put("projectName",projectBasicInformation.getProjectName());
//联系老师
mapHashMap.put("contacts",projectBasicInformation.getContacts());
//地址
mapHashMap.put("address",projectBasicInformation.getAddress());
//安装设备信息
mapHashMap.put("installEquipList", projectBasicInformation.getInstallationEquipmentList());
//数据分析
mapHashMap.put("dataAnalysisList",splitStrToListString(projectBasicInformation.getDataAnalysis()));
}else{
//如果安装设备信息为空,给默认值
mapHashMap.put("installEquipList", getInsEquipInfoDef());
mapHashMap.put("dataAnalysisList",splitStrToListString(null));
}
//项目总体情况projectGeneralSituation
ProjectGeneralSituation projectGeneralSituation = (ProjectGeneralSituation) proDetailMap.get("projectGeneralSituation");
if(projectGeneralSituation != null){
//报警总数
mapHashMap.put("alertTotal",projectGeneralSituation.getAlertTotal());
//日均报警数
mapHashMap.put("averageAlertNumber",projectGeneralSituation.getAverageAlertNumber());
//安全报警总数
mapHashMap.put("safetyAlertTotal",projectGeneralSituation.getSafetyAlertTotal());
//环境报警总数
mapHashMap.put("environmentalAlertTotal",projectGeneralSituation.getEnvironmentalAlertTotal());
//监测天数
mapHashMap.put("monitoringDays",projectGeneralSituation.getMonitoringDays());
//报警天数
mapHashMap.put("alertDays",projectGeneralSituation.getAlertDays());
//安全报警天数
mapHashMap.put("safetyAlertDays",projectGeneralSituation.getSafetyAlertDays());
//环境报警天数
mapHashMap.put("environmentalAlertDays",projectGeneralSituation.getEnvironmentalAlertDays());
}
//每日报警统计
List<ProjectEveryDayAlertStatistics> dailyAlarmStatis = (List<ProjectEveryDayAlertStatistics>) proDetailMap.get("projectEveryDayAlertStatisticsList");
mapHashMap.put("dailyAlarmStatisList",dailyAlarmStatis);
//环境报警统计
List<ProjectEnvironmentalAlertStatistics> envAlarmStatis = (List<ProjectEnvironmentalAlertStatistics>) proDetailMap.get("projectEnvironmentalAlertStatistics");
mapHashMap.put("envAlarmStatisList",envAlarmStatis);
}
//5、安全报警示例图片信息
List<ExportWordAlermImageVo> safeAlarmExamImageList = getSafeAlarmExamImage(proInfo.getProjectKeyId());
mapHashMap.put("safeAlarmExamImageList",safeAlarmExamImageList);
//6、施工现场图片【勘探和安装设备】
List<EmsDeploymentPlan> explorOrInsList = explorOrInsList(proInfo.getProjectKeyId());
if(!CollectionUtils.isEmpty(explorOrInsList)){
//勘探现场图片 两张
//学校门头
mapHashMap.put("schoolPhoto",explorOrInsList.get(0).getSchoolPhoto());
//学校场景1
mapHashMap.put("scenePhotoOne",explorOrInsList.get(0).getScenePhotoOne());
//安装环境设备位置 三张
mapHashMap.put("environmentalPosition",explorOrInsList.get(0).getEnvironmentalPosition());
//安装安全设备位置
mapHashMap.put("securityPosition",explorOrInsList.get(0).getSecurityPosition());
//学校场景二
mapHashMap.put("scenePhotoTwo",explorOrInsList.get(0).getScenePhotoTwo());
}
//7、附录 【环境报警阈值】
List<EnvAlarmThresholdVo> envAlarmThresholdList = getEnvAlarmThreshold(proInfo.getProjectKeyId());
mapHashMap.put("envAlarmThresholdList",envAlarmThresholdList);
//柱状图编号【此处编号是防止循环数据重复】
mapHashMap.put("barChartNum","bcn" + recordNum);
//曲线图编号
mapHashMap.put("curveNum","cn" + recordNum);
//学校门头编号
mapHashMap.put("schoolPhotoNum","spn" + recordNum);
//学校场景1编号
mapHashMap.put("scenePhotoOneNum","spon" + recordNum);
//安装环境设备位置编号
mapHashMap.put("environmentalPositionNum","epn" + recordNum);
//安装安全设备位置编号
mapHashMap.put("securityPositionNum","sypn" + recordNum);
//学校场景二编号
mapHashMap.put("scenePhotoTwoNum","sptn" + recordNum);
mapHashMap.put("proNo",proNo);
mapHashMap.put("proNm",proInfo.getProjectName());
listMapCatalog.add(mapHashMap);
//编号自增计算
proNo = proNo.add(BigDecimal.valueOf(0.1));
recordNum = recordNum.add(BigDecimal.valueOf(1));
}
}
return listMapCatalog;
}
/**
* 安装设备信息默认集合【防止空集合FTL文件崩溃】
* @return
*/
private List<InstallationEquipmentInformation> getInsEquipInfoDef(){
List<InstallationEquipmentInformation> defList = new ArrayList<>();
//录像机 DS-7604NB-K1 1
InstallationEquipmentInformation insEq = new InstallationEquipmentInformation();
insEq.setDeviceType("录像机");
insEq.setDeviceModel("DS-7604NB-K1");
insEq.setDeviceNumber(1);
defList.add(insEq);
return defList;
}
/**
* 数据分析分段处理【已句号分段】
*
* @param str
* @return
*/
public static List<InstallationEquipmentInformation> splitStrToListString(String str) {
List<InstallationEquipmentInformation> list = new ArrayList<>();
if (!StringUtil.isNullOrEmpty(str)) {
String[] split = freemarker.template.utility.StringUtil.split(str, '。');
InstallationEquipmentInformation info = null;
//参数中只有一个值
if(split == null){
info = new InstallationEquipmentInformation();
info.setDataAnalysis(str);
list.add(info);
return list ;
}
for (String string : split) {
info = new InstallationEquipmentInformation();
if(StringUtil.isNullOrEmpty(string)){
continue;
}else {
info.setDataAnalysis(string + "。");
}
list.add(info);
}
}
return list;
}
/**
* 根据项目id获取每日报警信息
* @param exprotWordParam
* @return
*/
public List<Map<String,Object>> getDailyAlarmByProjectId(ExprotWordParam exprotWordParam){
//项目每日报警统计List
List<ProjectEveryDayAlertStatistics> safeList = exportWordDao.getProjectEveryDayAlertStatisticsListByProjectId(exprotWordParam.getProjectId());
List<Map<String,Object>> dailyAlarm = new ArrayList<>();
Map<String,Object> dataValMap = null;
List<Map<String,Object>> xData = null;
//环境和安全
Map<String,Object> envAndSafeMap = null;
if(!CollectionUtils.isEmpty(safeList)){
for(ProjectEveryDayAlertStatistics dayAlert :safeList){
xData = new ArrayList<>();
dataValMap = new HashMap<>();
dataValMap.put("yData",dayAlert.getAlertTime());
envAndSafeMap = new HashMap<>();
envAndSafeMap.put("name","环境报警");
envAndSafeMap.put("values",dayAlert.getEnvironmentalAlertEveryDayNumber());
xData.add(envAndSafeMap);
envAndSafeMap = new HashMap<>();
envAndSafeMap.put("name","安全报警");
envAndSafeMap.put("values",dayAlert.getSafetyAlertEveryDayNumber());
xData.add(envAndSafeMap);
dataValMap.put("xData",xData);
dailyAlarm.add(dataValMap);
}
}
return dailyAlarm;
}
/**
* 根据项目id获取环境报警统计信息
* @param exprotWordParam
* @return
*/
public List<Map<String,Object>> getEnvAlarmByProjectId(ExprotWordParam exprotWordParam){
//项目每日报警统计List
//项目环境报警统计List
List<ProjectEnvironmentalAlertStatistics> envList = exportWordDao.getProjectEnvironmentalAlertStatisticsListByProjectId(exprotWordParam.getProjectId());
if(!CollectionUtils.isEmpty(envList) && envList.size() !=24){
List<ProjectEnvironmentalAlertStatistics> projectEnvironmentalAlertStatisticsList = new ArrayList<>();
for(int i = 0; i <=23 ; i++){
ProjectEnvironmentalAlertStatistics p = new ProjectEnvironmentalAlertStatistics();
p.setAlertTime(i);
projectEnvironmentalAlertStatisticsList.add(p);
}
for(int i = 0 ; i < envList.size() ; i++){
projectEnvironmentalAlertStatisticsList.set(envList.get(i).getAlertTime(),envList.get(i));
}
envList =projectEnvironmentalAlertStatisticsList;
}
List<Map<String,Object>> envAlarm = new ArrayList<>();
Map<String,Object> dataValMap = null;
if(!CollectionUtils.isEmpty(envList)){
for(ProjectEnvironmentalAlertStatistics envAlert :envList){
dataValMap = new HashMap<>();
dataValMap.put("xData",envAlert.getAlertTime());
dataValMap.put("yData",getEnvYDataList(envAlert));
envAlarm.add(dataValMap);
}
}
return envAlarm;
}
/**
* 获取环境报警统计信息Y轴
* @param envAlert
* @return
*/
private List<Map<String,Object>> getEnvYDataList(ProjectEnvironmentalAlertStatistics envAlert){
List<Map<String,Object>> yData = new ArrayList<>();
//环境
Map<String,Object> envMap = null;
envMap = new HashMap<>();
envMap.put("name","噪音");
envMap.put("values",envAlert.getNoise());
yData.add(envMap);
envMap = new HashMap<>();
envMap.put("name","TSP");
envMap.put("values",envAlert.getTSP());
yData.add(envMap);
envMap = new HashMap<>();
envMap.put("name","PM2.5");
envMap.put("values",envAlert.getPM25());
yData.add(envMap);
envMap = new HashMap<>();
envMap.put("name","PM10");
envMap.put("values",envAlert.getPM10());
yData.add(envMap);
return yData;
}
}
导出工具ExportWordUtils
package com.sjasoft.cloud.admin.utils;
import java.io.*;
import java.net.URLEncoder;
import java.util.Map;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import com.sjasoft.cloud.admin.dto.ems.MultipartFileDto;
import com.sjasoft.cloud.admin.service.ems.ExportWordService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.commons.io.FileUtils;
import org.apache.http.entity.ContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
public class ExportWordUtils {
private static Logger logger = LoggerFactory.getLogger(ExportWordService.class);
//配置信息
private static Configuration configuration = null;
//利用ExportWordUtils的类加载器动态获得模板文件的位置
private static final InputStream streamTemp = ExportWordUtils.class.getClassLoader().getResourceAsStream("doc/simpleFTL.ftl");
static {
configuration = new Configuration();
configuration.setDefaultEncoding("utf-8");
try {
File fileTemp = new File("docTemp");
File fileFtlTemp = new File(fileTemp,"simpleFTL.ftl");
if(!fileTemp.exists()){
fileTemp.mkdir();
}
if(!fileFtlTemp.isFile()){
fileFtlTemp.createNewFile();
}
FileUtils.copyInputStreamToFile(streamTemp,fileFtlTemp);
logger.info("打印当前工程模板内容:{}",streamTemp);
//logger.info("打印当前工程模板路径:{}",templateFolder);
configuration.setDirectoryForTemplateLoading(fileTemp);
} catch (IOException e) {
e.printStackTrace();
}
}
/***********************************此处代码打成jar会出现找不到模板的问题**************************************/
// private static final String templateFolder = ExportWordUtils.class.getClassLoader().getResource("doc").getPath();
// //测试private static final String templateFolder = "D:/1_FTL";
// static {
// configuration = new Configuration();
// configuration.setDefaultEncoding("utf-8");
// try {
// logger.info("打印当前工程模板路径:{}",templateFolder);
// configuration.setDirectoryForTemplateLoading(new File(templateFolder));
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
/*************************************************************************/
private ExportWordUtils() {
throw new AssertionError();
}
/**
* 复制模板导出word文档
* @param response
* @param map 内容
* @param fileName 文件名
* @param ftlFile 复制模板名
* @throws IOException
*/
public static MultipartFile exportMillCertificateWord(HttpServletResponse response, Map map, String fileName, String ftlFile) throws IOException {
Template freemarkerTemplate = configuration.getTemplate(ftlFile);
File file = null;
InputStream fin = null;
ServletOutputStream out = null;
MultipartFile multipartFile = null;
try {
// 调用工具类的createDoc方法生成Word文档
file = createDoc(map,freemarkerTemplate);
fin = new FileInputStream(file);
response.setCharacterEncoding("utf-8");
//response.setContentType("application/msword");
response.setContentType("application/octet-stream");
//放开权限
response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
response.setHeader("Content-Disposition", "attachment;filename="
.concat(String.valueOf(URLEncoder.encode(fileName, "UTF-8"))));
out = response.getOutputStream();
// 缓冲区
byte[] buffer = new byte[512];
//定义字节数组字节流循环写入
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int bytesToRead = -1;
// 通过循环将读入的Word文件的内容输出到浏览器中
while((bytesToRead = fin.read(buffer)) != -1) {
out.write(buffer, 0, bytesToRead);
bos.write(buffer,0,bytesToRead);
}
//字节数组字节流转为inputStream
InputStream input = new ByteArrayInputStream(bos.toByteArray());
multipartFile = new MultipartFileDto(
fileName,fileName
, ContentType.APPLICATION_OCTET_STREAM.toString(), input);
} finally {
if(fin != null) fin.close();
if(out != null) out.close();
if(file != null) file.delete(); // 删除临时文件
logger.info("导出成功!!!!!!!");
}
return multipartFile;
}
private static File createDoc(Map<?, ?> dataMap, Template template) {
String name = "sellPlan.doc";
File f = new File(name);
Template t = template;
try {
// 这个地方不能使用FileWriter因为需要指定编码类型否则生成的Word文档会因为有无法识别的编码而无法打开
Writer w = new OutputStreamWriter(new FileOutputStream(f), "utf-8");
t.process(dataMap, w);
w.close();
} catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
return f;
}
}
模板文件存储个人网盘中