diff --git a/hzims-service-api/inspect-api/src/main/java/com/hnac/hzinfo/inspect/plan/vo/PlanVO.java b/hzims-service-api/inspect-api/src/main/java/com/hnac/hzinfo/inspect/plan/vo/PlanVO.java index f2dee4b..d12668a 100644 --- a/hzims-service-api/inspect-api/src/main/java/com/hnac/hzinfo/inspect/plan/vo/PlanVO.java +++ b/hzims-service-api/inspect-api/src/main/java/com/hnac/hzinfo/inspect/plan/vo/PlanVO.java @@ -4,6 +4,8 @@ package com.hnac.hzinfo.inspect.plan.vo; import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.ser.std.NullSerializer; import com.google.common.collect.Lists; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -184,4 +186,8 @@ public class PlanVO extends TenantEntity implements Serializable { /** hzims add end **/ + @ApiModelProperty(value = "消息模板ID") + @JsonSerialize(nullsUsing = NullSerializer.class) + private Long messageTemplateId; + } diff --git a/hzims-service-api/inspect-api/src/main/java/com/hnac/hzinfo/inspect/task/entity/TaskEntity.java b/hzims-service-api/inspect-api/src/main/java/com/hnac/hzinfo/inspect/task/entity/TaskEntity.java index 83c4274..6743e12 100644 --- a/hzims-service-api/inspect-api/src/main/java/com/hnac/hzinfo/inspect/task/entity/TaskEntity.java +++ b/hzims-service-api/inspect-api/src/main/java/com/hnac/hzinfo/inspect/task/entity/TaskEntity.java @@ -171,4 +171,8 @@ public class TaskEntity extends TenantEntity { @JsonSerialize(nullsUsing = NullSerializer.class) private Long messageTemplateId; + @ApiModelProperty(value = "消息推送状态") + @JsonSerialize(nullsUsing = NullSerializer.class) + private Boolean pushStatus; + } diff --git a/hzims-service/inspect/src/main/java/com/hnac/hzinfo/inspect/task/aspect/TaskGenerateAspect.java b/hzims-service/inspect/src/main/java/com/hnac/hzinfo/inspect/task/aspect/TaskGenerateAspect.java index 3a7b5bb..d437893 100644 --- a/hzims-service/inspect/src/main/java/com/hnac/hzinfo/inspect/task/aspect/TaskGenerateAspect.java +++ b/hzims-service/inspect/src/main/java/com/hnac/hzinfo/inspect/task/aspect/TaskGenerateAspect.java @@ -76,10 +76,16 @@ public class TaskGenerateAspect { PlanEntity plan = (PlanEntity) args[0]; List list = taskService.list( Wrappers.lambdaQuery().eq(TaskEntity::getPlanId,plan.getId()) + .isNull(TaskEntity::getPushStatus) ); if(CollectionUtil.isNotEmpty(list)) { - list.forEach(this::pushMessageByTask); + list.forEach(task -> { + this.pushMessageByTask(task); + task.setPushStatus(true); + taskService.updateById(task); + }); } + TaskEntity task = JSONObject.parseObject(JSON.toJSONString(args[0]),TaskEntity.class); this.pushMessageByTask(task); } @@ -91,6 +97,7 @@ public class TaskGenerateAspect { * @param taskEntity 巡检任务 */ private void pushMessageByTask(TaskEntity taskEntity) { + log.info("======================进入消息推送======================"); PlanMsgRecordDto recordDto = new PlanMsgRecordDto(); recordDto.setDeptId(taskEntity.getCreateDept()); recordDto.setTemplateId(taskEntity.getMessageTemplateId()); @@ -114,12 +121,13 @@ public class TaskGenerateAspect { recordDto.setPlanTime(taskEntity.getPlanStartTime()); recordDto.setSmsParam(JSON.toJSONString(smsMap)); recordDto.setContent("任务“"+ taskEntity.getPlanName() + "”的计划执行时间是:" + df.format(taskEntity.getPlanStartTime())+ " —— " + df.format(taskEntity.getPlanEndTime())); + log.info("巡检任务开始,推送对象:{}",JSON.toJSONString(recordDto)); messageClient.planSendMessage(recordDto); // 消息结束前提醒 -/* smsMap.put("two",df.format(taskEntity.getPlanEndTime())); + smsMap.put("two",df.format(taskEntity.getPlanEndTime())); recordDto.setPlanTime(taskEntity.getPlanEndTime()); recordDto.setSmsParam(JSON.toJSONString(smsMap)); - messageClient.planSendMessage(recordDto);*/ + messageClient.planSendMessage(recordDto); }); } } diff --git a/hzims-service/inspect/src/main/resources/db/1.0.0.sql b/hzims-service/inspect/src/main/resources/db/1.0.0.sql index 9053136..9747c3a 100644 --- a/hzims-service/inspect/src/main/resources/db/1.0.0.sql +++ b/hzims-service/inspect/src/main/resources/db/1.0.0.sql @@ -1,4 +1,6 @@ -- 巡检计划添加消息模板字段 alter table `hz_st_re_plan` add column `message_template_id` bigint(20) comment '消息模板ID'; -- 巡检任务添加消息模板字段 -alter table `hz_st_ex_task` add column `message_template_id` bigint(20) comment '消息模板ID'; \ No newline at end of file +alter table `hz_st_ex_task` add column `message_template_id` bigint(20) comment '消息模板ID'; + +alter table hz_st_ex_task add COLUMN `push_status` bigint(1) default null comment '推送状态'; \ No newline at end of file diff --git a/hzims-service/message/src/main/java/com/hnac/hzims/message/schedule/MessagePushSchedule.java b/hzims-service/message/src/main/java/com/hnac/hzims/message/schedule/MessagePushSchedule.java index 97357e2..fa08db4 100644 --- a/hzims-service/message/src/main/java/com/hnac/hzims/message/schedule/MessagePushSchedule.java +++ b/hzims-service/message/src/main/java/com/hnac/hzims/message/schedule/MessagePushSchedule.java @@ -24,7 +24,9 @@ import org.springblade.core.tool.utils.Func; import org.springblade.core.tool.utils.ObjectUtil; import org.springframework.stereotype.Component; +import java.time.LocalDate; import java.time.LocalDateTime; +import java.time.LocalTime; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -59,7 +61,7 @@ public class MessagePushSchedule { LambdaQueryWrapper lqw = Wrappers.lambdaQuery() .eq(MessagePushRecordEntity::getStatus, MessageConstants.NOT_PUSH) .eq(MessagePushRecordEntity::getTemplateId,template.getId()) - .ge(MessagePushRecordEntity::getPlanTime, now) + .ge(MessagePushRecordEntity::getPlanTime, LocalDateTime.of(LocalDate.now(), LocalTime.MIN)) .le(MessagePushRecordEntity::getPlanTime, endTime); List list = recordService.list(lqw); if(CollectionUtil.isEmpty(list) || list.size() == 0) { @@ -77,28 +79,30 @@ public class MessagePushSchedule { * @return void **/ private void sendMessage(List list) { - Map> collect = list.stream().collect(Collectors.groupingBy(MessagePushRecordEntity::getAccount)); - String type = list.get(0).getType(); - IMessageService service = MessageFactory.getMessageSend(type); - collect.forEach((account,records) -> { - MessagePushRecordEntity request = records.get(0); - // 完善推送内容 - request.setContent(this.getPushContent(type,records)); - if(MessageConstants.SMS_PUSH.equals(type)) { - request.setSmsParam(request.getContent()); - } - request.setMessageId(IdWorker.getId()); - Boolean flag = service.send(request); - if(!flag) { - return; - } - List ids = records.stream().map(MessagePushRecordEntity::getId).collect(Collectors.toList()); - // 更新消息推送状态 - LambdaUpdateWrapper lwq = Wrappers.lambdaUpdate() - .set(MessagePushRecordEntity::getStatus, flag ? MessageConstants.PUSH_SUCCESS : MessageConstants.PUSH_FAILED) - .set(MessagePushRecordEntity::getPushTime,LocalDateTime.now()) - .in(MessagePushRecordEntity::getId, ids); - recordService.update(lwq); + Map> typeGroup = list.stream().collect(Collectors.groupingBy(MessagePushRecordEntity::getType)); + typeGroup.forEach((type,typeList) -> { + Map> collect = typeList.stream().collect(Collectors.groupingBy(MessagePushRecordEntity::getAccount)); + IMessageService service = MessageFactory.getMessageSend(type); + collect.forEach((account,records) -> { + MessagePushRecordEntity request = records.get(0); + // 完善推送内容 + request.setContent(this.getPushContent(type,records)); + if(MessageConstants.SMS_PUSH.equals(type)) { + request.setSmsParam(request.getContent()); + } + request.setMessageId(IdWorker.getId()); + Boolean flag = service.send(request); + if(!flag) { + return; + } + List ids = records.stream().map(MessagePushRecordEntity::getId).collect(Collectors.toList()); + // 更新消息推送状态 + LambdaUpdateWrapper lwq = Wrappers.lambdaUpdate() + .set(MessagePushRecordEntity::getStatus, flag ? MessageConstants.PUSH_SUCCESS : MessageConstants.PUSH_FAILED) + .set(MessagePushRecordEntity::getPushTime,LocalDateTime.now()) + .in(MessagePushRecordEntity::getId, ids); + recordService.update(lwq); + }); }); } diff --git a/hzims-service/message/src/main/java/com/hnac/hzims/message/service/impl/MessagePushRecordServiceImpl.java b/hzims-service/message/src/main/java/com/hnac/hzims/message/service/impl/MessagePushRecordServiceImpl.java index 9237990..437cacc 100644 --- a/hzims-service/message/src/main/java/com/hnac/hzims/message/service/impl/MessagePushRecordServiceImpl.java +++ b/hzims-service/message/src/main/java/com/hnac/hzims/message/service/impl/MessagePushRecordServiceImpl.java @@ -95,10 +95,10 @@ public class MessagePushRecordServiceImpl extends BaseServiceImpl platformTypes = Lists.newArrayList(PlatformType.Android, PlatformType.IOS); diff --git a/hzims-service/operational/pom.xml b/hzims-service/operational/pom.xml index 8ed6b02..8e5a5fd 100644 --- a/hzims-service/operational/pom.xml +++ b/hzims-service/operational/pom.xml @@ -92,6 +92,22 @@ cn.afterturn easypoi-base + + + org.apache.poi + ooxml-schemas + 1.4 + + + org.jfree + jcommon + 1.0.24 + + + org.jfree + jfreechart + 1.5.0 + cn.afterturn easypoi-annotation @@ -226,7 +242,6 @@ - diff --git a/hzims-service/operational/src/main/java/com/hnac/hzims/operational/main/controller/AreaMonthReportController.java b/hzims-service/operational/src/main/java/com/hnac/hzims/operational/main/controller/AreaMonthReportController.java index 40733fc..a5973f1 100644 --- a/hzims-service/operational/src/main/java/com/hnac/hzims/operational/main/controller/AreaMonthReportController.java +++ b/hzims-service/operational/src/main/java/com/hnac/hzims/operational/main/controller/AreaMonthReportController.java @@ -1,11 +1,14 @@ package com.hnac.hzims.operational.main.controller; +import cn.afterturn.easypoi.entity.ImageEntity; import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport; import com.hnac.hzims.common.logs.annotation.OperationAnnotation; import com.hnac.hzims.common.logs.enums.BusinessType; import com.hnac.hzims.common.logs.enums.OperatorType; import com.hnac.hzims.operational.main.service.IAreaMonthReportService; import com.hnac.hzims.operational.main.vo.AreaMonthReportVo; +import com.hnac.hzims.operational.util.JFreeUtil; +import com.hnac.hzims.operational.util.WordUtils; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; @@ -21,7 +24,9 @@ import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletResponse; import javax.validation.constraints.NotNull; +import java.util.ArrayList; import java.util.Date; +import java.util.HashMap; import java.util.List; @RestController @@ -31,36 +36,82 @@ import java.util.List; @Slf4j public class AreaMonthReportController extends BladeController { - @NotNull - private final IAreaMonthReportService service; + @NotNull + private final IAreaMonthReportService service; - @ApiLog - @ApiOperationSupport(order = 1) - @ApiOperation("生成区域月报") - @GetMapping("/loadMonthReport") - public R loadMonthReport() { - service.loadMonthReport(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"),1); - return R.success("success"); - } + @ApiLog + @ApiOperationSupport(order = 1) + @ApiOperation("生成区域月报") + @GetMapping("/loadMonthReport") + public R loadMonthReport() { + service.loadMonthReport(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"), 1); + return R.success("success"); + } - @ApiLog - @ApiOperationSupport(order = 2) - @ApiOperation("获取区域月报") - @GetMapping("/getAreaMonthReport") - @OperationAnnotation( - moduleName = "生产月报", - title = "水电生产运行月报",operatorType = OperatorType.MOBILE,businessType = BusinessType.GENCODE, - action = "获取区域月报") - public R> getAreaMonthReport(@ApiParam(value = "日期-年月", required = true) String date) { - return service.getReport(date); - } + @ApiLog + @ApiOperationSupport(order = 2) + @ApiOperation("获取区域月报") + @GetMapping("/getAreaMonthReport") + @OperationAnnotation( + moduleName = "生产月报", + title = "水电生产运行月报", operatorType = OperatorType.MOBILE, businessType = BusinessType.GENCODE, + action = "获取区域月报") + public R> getAreaMonthReport(@ApiParam(value = "日期-年月", required = true) String date) { + return service.getReport(date); + } - @ApiLog - @ApiOperationSupport(order = 3) - @ApiOperation("导出区域月报") - @GetMapping("/exportAreaMonthReport") - public R exportAreaMonthReport(HttpServletResponse response,@ApiParam(value = "日期-年月", required = true) String date) { - return service.export(response,date); - } + @ApiLog + @ApiOperationSupport(order = 3) + @ApiOperation("导出区域月报") + @GetMapping("/exportAreaMonthReport") + public R exportAreaMonthReport(HttpServletResponse response, @ApiParam(value = "日期-年月", required = true) String date) { + return service.export(response, date); + } + + @ApiLog + @ApiOperationSupport(order = 3) + @ApiOperation("测试导出模板相关数据") + @GetMapping("/exportAreaMonthReport3333") + public R exportAreaMonthReport333(HttpServletResponse response, @ApiParam(value = "日期-年月", required = true) String date) { + HashMap map = new HashMap<>(4); + + //模拟饼状图数据 + HashMap datas = new HashMap<>(3); + datas.put("华自", 10); + datas.put("华自二号", 20); + datas.put("华自三号", 40); + ImageEntity imageEntity = JFreeUtil.pieChart("测试", datas, 300, 200); + map.put("picture", imageEntity); + //模拟柱状图图数据 + String[] monthArray = {"一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月"}; + double[] value = {20, 30, 25, 50, 40, 25, 50, 40}; + ImageEntity lineEntity = JFreeUtil.lineChart("测试111", monthArray, value,300, 200); + map.put("lineEntity", lineEntity); + + //模拟其它普通数据 + map.put("username", "张三"); + map.put("date", "2019-10-10"); + map.put("desc", "测试"); + map.put("boo", true); + + //模拟表格数据 + ArrayList> list = new ArrayList<>(2); + HashMap temp = new HashMap<>(3); + temp.put("sn", "1"); + temp.put("name", "第一个人"); + temp.put("age", "23"); + list.add(temp); + temp = new HashMap<>(3); + temp.put("sn", "2"); + temp.put("name", "第二个人"); + temp.put("age", "24"); + list.add(temp); + map.put("personlist", list); +// //todo +// map.put("personlist", list); + //word模板相对路径、word生成路径、word生成的文件名称、数据源 + WordUtils.exportWord("template/demo2.docx", "F:/", "生成文件.docx", map); + return R.success("测试成功"); + } } diff --git a/hzims-service/operational/src/main/java/com/hnac/hzims/operational/station/service/impl/StationServiceImpl.java b/hzims-service/operational/src/main/java/com/hnac/hzims/operational/station/service/impl/StationServiceImpl.java index 3322ece..85ee6c1 100644 --- a/hzims-service/operational/src/main/java/com/hnac/hzims/operational/station/service/impl/StationServiceImpl.java +++ b/hzims-service/operational/src/main/java/com/hnac/hzims/operational/station/service/impl/StationServiceImpl.java @@ -71,10 +71,6 @@ public class StationServiceImpl extends BaseServiceImpl { - throw new ServiceException("创建/修改机构失败!"); - }); LambdaQueryWrapper lwq; if (Func.isEmpty(req.getId())) { lwq = Wrappers.lambdaQuery() @@ -88,6 +84,10 @@ public class StationServiceImpl extends BaseServiceImpl { throw new ServiceException("该站点名/编码已有对应记录,请找到相应记录做修改处理"); }); + // 新建站点的所属机构 + Assert.isTrue(this.buildDept(req), () -> { + throw new ServiceException("创建/修改机构失败!"); + }); Optional sort = Optional.ofNullable(this.getStationMaxOrder()); req.setSort(sort.isPresent() ? sort.get() + 1 : 1); Assert.isTrue(this.saveOrUpdate(req), () -> { diff --git a/hzims-service/operational/src/main/java/com/hnac/hzims/operational/util/JFreeUtil.java b/hzims-service/operational/src/main/java/com/hnac/hzims/operational/util/JFreeUtil.java new file mode 100644 index 0000000..a6b7fa9 --- /dev/null +++ b/hzims-service/operational/src/main/java/com/hnac/hzims/operational/util/JFreeUtil.java @@ -0,0 +1,712 @@ +package com.hnac.hzims.operational.util; + +import cn.afterturn.easypoi.entity.ImageEntity; +import cn.hutool.core.lang.Assert; +import lombok.extern.slf4j.Slf4j; +import org.jfree.chart.ChartFactory; +import org.jfree.chart.ChartUtils; +import org.jfree.chart.JFreeChart; +import org.jfree.chart.StandardChartTheme; +import org.jfree.chart.axis.CategoryAxis; +import org.jfree.chart.axis.NumberAxis; +import org.jfree.chart.labels.StandardPieSectionLabelGenerator; +import org.jfree.chart.plot.CategoryPlot; +import org.jfree.chart.plot.PiePlot; +import org.jfree.chart.renderer.category.BarRenderer; +import org.jfree.chart.renderer.category.CategoryItemRenderer; +import org.jfree.chart.renderer.category.LineAndShapeRenderer; +import org.jfree.data.category.DefaultCategoryDataset; +import org.jfree.data.general.DefaultPieDataset; + +import java.awt.*; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.util.Map; + +@Slf4j +public class JFreeUtil { + + private static String tempImgPath = "D:\\tempJfree.jpeg"; + private static String tempImgPath2 = "D:\\tempJfree2.jpeg"; + + /** + * 将图片转化为字节数组 + * + * @return 字节数组 + */ + private static byte[] imgToByte(String tempImgPath) { + File file = new File(tempImgPath); + byte[] buffer = null; + try { + FileInputStream fis = new FileInputStream(file); + ByteArrayOutputStream bos = new ByteArrayOutputStream(1000); + byte[] b = new byte[1000]; + int n; + while ((n = fis.read(b)) != -1) { + bos.write(b, 0, n); + } + fis.close(); + bos.close(); + buffer = bos.toByteArray(); + } catch (IOException e) { + log.error(e.getMessage()); + } + //删除临时文件 + file.delete(); + return buffer; + } + + public static ImageEntity pieChart(String title, Map datas, int width, int height) { + + //创建主题样式 + StandardChartTheme standardChartTheme = new StandardChartTheme("CN"); + //设置标题字体 + standardChartTheme.setExtraLargeFont(new Font("宋体", Font.BOLD, 20)); + //设置图例的字体 + standardChartTheme.setRegularFont(new Font("宋体", Font.PLAIN, 15)); + //设置轴向的字体 + standardChartTheme.setLargeFont(new Font("宋体", Font.PLAIN, 15)); + //设置主题样式 + ChartFactory.setChartTheme(standardChartTheme); + + //根据jfree生成一个本地饼状图 + DefaultPieDataset pds = new DefaultPieDataset(); + datas.forEach(pds::setValue); + //图标标题、数据集合、是否显示图例标识、是否显示tooltips、是否支持超链接 + JFreeChart chart = ChartFactory.createPieChart(title, pds, true, false, false); + //设置抗锯齿 + chart.setTextAntiAlias(false); + PiePlot plot = (PiePlot) chart.getPlot(); + plot.setNoDataMessage("暂无数据"); + //忽略无值的分类 + plot.setIgnoreNullValues(true); + plot.setBackgroundAlpha(0f); + //设置标签阴影颜色 + plot.setShadowPaint(new Color(255, 255, 255)); + //设置标签生成器(默认{0}) + plot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0}({1})/{2}")); + try { + ChartUtils.saveChartAsJPEG(new File(tempImgPath), chart, width, height); + } catch (IOException e1) { + log.error("生成饼状图失败!"); + } + ImageEntity imageEntity = new ImageEntity(imgToByte(tempImgPath), width, height); + Assert.notNull(imageEntity.getData(), "生成饼状图对象失败!"); + return imageEntity; + } +// public static ImageEntity lineChart(String title, Map datas, int width, int height) { +// +// //创建主题样式 +// StandardChartTheme standardChartTheme = new StandardChartTheme("CN"); +// //设置标题字体 +// standardChartTheme.setExtraLargeFont(new Font("宋体", Font.BOLD, 20)); +// //设置图例的字体 +// standardChartTheme.setRegularFont(new Font("宋体", Font.PLAIN, 15)); +// //设置轴向的字体 +// standardChartTheme.setLargeFont(new Font("宋体", Font.PLAIN, 15)); +// //设置主题样式 +// ChartFactory.setChartTheme(standardChartTheme); +// +// //根据jfree生成一个本地饼状图 +// DefaultPieDataset pds = new DefaultPieDataset(); +// datas.forEach(pds::setValue); +// LineAndShapeRenderer pdsLine = new LineAndShapeRenderer(); +// datas.forEach(pdsLine::setValue); +// //图标标题、数据集合、是否显示图例标识、是否显示tooltips、是否支持超链接 +// JFreeChart chart = ChartFactory.createPieChart(title, pds, true, false, false); +// JFreeChart chart2 = ChartFactory.createLineChart(title, pdsLine, true, false, false); +// //设置抗锯齿 +// chart.setTextAntiAlias(false); +// PiePlot plot = (PiePlot) chart.getPlot(); +// plot.setNoDataMessage("暂无数据"); +// //忽略无值的分类 +// plot.setIgnoreNullValues(true); +// plot.setBackgroundAlpha(0f); +// //设置标签阴影颜色 +// plot.setShadowPaint(new Color(255,255,255)); +// //设置标签生成器(默认{0}) +// plot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0}({1})/{2}")); +// try { +// ChartUtils.saveChartAsJPEG(new File(tempImgPath), chart, width, height); +// } catch (IOException e1) { +// log.error("生成饼状图失败!"); +// } +// ImageEntity imageEntity = new ImageEntity(imgToByte(), width, height); +// Assert.notNull(imageEntity.getData(),"生成饼状图对象失败!"); +// return imageEntity; +// } + + public static ImageEntity lineChart( String title,String[] monthArray,double[] value,int width, int height) { + // 创建数据 + DefaultCategoryDataset dataset = new DefaultCategoryDataset(); + dataset.addValue(1.0, "A", "Ⅰ"); + dataset.addValue(3.0, "A", "Ⅱ"); + dataset.addValue(5.0, "A", "Ⅲ"); + dataset.addValue(5.0, "A", "Ⅳ"); + dataset.addValue(5.0, "B", "Ⅰ"); + dataset.addValue(6.0, "B", "Ⅱ"); + dataset.addValue(10.0, "B", "Ⅲ"); + dataset.addValue(4.0, "B", "Ⅳ"); + + // 创建CategoryPlot对象 + CategoryPlot plot = new CategoryPlot(); + + // 添加第一个数据集并渲染为line + CategoryItemRenderer lineRenderer = new LineAndShapeRenderer(); + plot.setDataset(0, dataset); + plot.setRenderer(0, lineRenderer); + + // 添加第二个数据集并渲染为线条bar + CategoryItemRenderer baRenderer = new BarRenderer(); + plot.setDataset(1, dataset); + plot.setRenderer(1, baRenderer); + + // 设置坐标轴 + plot.setDomainAxis(new CategoryAxis("Time")); + plot.setRangeAxis(new NumberAxis("Value")); + + // 创建JFreeChart对象 + JFreeChart chart = new JFreeChart(plot); + + try { + ChartUtils.saveChartAsJPEG(new File(tempImgPath2), chart, width, height); + } catch (IOException e) { + e.printStackTrace(); + } + ImageEntity imageEntity = new ImageEntity(imgToByte(tempImgPath2), width, height); + Assert.notNull(imageEntity.getData(),"生成饼状图对象失败!"); + return imageEntity; + } +// public static ImageEntity lineChart( String title,String[] monthArray,double[] value,int width, int height) { +// //如果不使用Font,中文将显示不出来 +// Font font = new Font("新宋体", Font.BOLD, 15); +// // 创建数据 +// Map> datas = new HashMap>(); +// for (int i = 0; i < monthArray.length; i++) { +// Map map = new HashMap(); +// map.put("故障数量", value[i]); +// datas.put(monthArray[i], map); +// } +// JFreeChart chart = createLineChart(title, datas, "月份", "故障次数(次)", font); +// try { +// ChartUtils.saveChartAsJPEG(new File(tempImgPath), chart, 800, 600); +// } catch (IOException e) { +// e.printStackTrace(); +// } +// ImageEntity imageEntity = new ImageEntity(imgToByte(), 800, 600); +// Assert.notNull(imageEntity.getData(),"生成饼状图对象失败!"); +// return imageEntity; +// } +// +// public static JFreeChart createLineChart(String title, Map> data, String type, String unit, Font font) { +// try { +// DefaultCategoryDataset ds = new DefaultCategoryDataset(); +// Set>> set1 = data.entrySet(); +// Iterator iterator1 = set1.iterator(); +// Iterator iterator2; +// HashMap map; +// Set> set2; +// Map.Entry entry1; +// Map.Entry entry2; +// while (iterator1.hasNext()) { +// entry1 = (Map.Entry) iterator1.next(); +// map = (HashMap) entry1.getValue(); +// set2 = map.entrySet(); +// iterator2 = set2.iterator(); +// while (iterator2.hasNext()) { +// entry2 = (Map.Entry) iterator2.next(); +// ds.setValue(Double.parseDouble(entry2.getValue().toString()), entry2.getKey().toString(), entry1.getKey().toString()); +// } +// } +// +// //创建折线图,折线图分水平显示和垂直显示两种 +// // //2D折线图 +// JFreeChart chart = ChartFactory.createLineChart(title, type, unit, ds, PlotOrientation.VERTICAL, true, true, true); +// // //3D折线图 +//// JFreeChart chart2 = ChartFactory.createLineChart3D(title, type, unit, ds, PlotOrientation.VERTICAL, true, true, false); +// +// //设置整个图片的标题字体 +// chart.getTitle().setFont(font); +// +// //设置提示条字体 +// font = new Font("宋体", Font.BOLD, 15); +// chart.getLegend().setItemFont(font); +// +// //得到绘图区 +// CategoryPlot plot = (CategoryPlot) chart.getPlot(); +// //得到绘图区的域轴(横轴),设置标签的字体 +// plot.getDomainAxis().setLabelFont(font); +// +// // 设置背景透明度 +// plot.setBackgroundAlpha(0.1f); +// // 设置网格横线颜色 +// plot.setRangeGridlinePaint(Color.gray); +// // 设置网格横线大小 +// plot.setDomainGridlineStroke(new BasicStroke(0.2F)); +// plot.setRangeGridlineStroke(new BasicStroke(0.2F)); +// +// //设置横轴标签项字体 +// plot.getDomainAxis().setTickLabelFont(font); +// +// // 生成折线图上的数字 +// //绘图区域(红色矩形框的部分) +// LineAndShapeRenderer lineAndShapeRenderer = (LineAndShapeRenderer) plot.getRenderer(); +// lineAndShapeRenderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator()); +// //设置图表上的数字可见 +// lineAndShapeRenderer.setBaseItemLabelsVisible(true); +// //设置图表上的数字字体 +// lineAndShapeRenderer.setBaseItemLabelFont(new Font("宋体", Font.BOLD, 15)); +// +// //设置折线图拐角上的正方形 +// //创建一个正方形 +// Rectangle shape = new Rectangle(4, 4); +// lineAndShapeRenderer.setSeriesShape(0, shape); +// //设置拐角上图形可见 +// lineAndShapeRenderer.setSeriesShapesVisible(0, true); +// +// /*// 获取显示线条的对象 +// LineAndShapeRenderer lasp = (LineAndShapeRenderer) plot.getRenderer(); +// // 设置拐点是否可见/是否显示拐点 +// lasp.setBaseShapesVisible(true); +// // 设置拐点不同用不同的形状 +// lasp.setDrawOutlines(true); +// // 设置线条是否被显示填充颜色 +// lasp.setUseFillPaint(true); +// // 设置拐点颜色 +// lasp.setBaseFillPaint(Color.blue);//蓝色*/ +// //设置范围轴(纵轴)字体 +// font = new Font("宋体", Font.BOLD, 18); +// plot.getRangeAxis().setLabelFont(font); +//// plot.setForegroundAlpha(1.0f); +// return chart; +// } catch (Exception e) { +// e.printStackTrace(); +// return null; +// } +// } +// +// /** +// * 生成折线图 +// * 1.解析数据
+// * 2.迭代数据,产出图片数据流,并添加到List
+// * +// * @throws IOException +// */ +// public ArrayList createLineAndShapeChart(double[][] data, String[] rowKeys, String[] columnKeys, ChartEntity entity) throws IOException { +// ArrayList list = new ArrayList(); +// byte[] bytes = new byte[]{}; +// // 解析数据 +// Map map = this.parseDataForBarPage(data, rowKeys, columnKeys); +// int pageNum = Integer.parseInt("" + map.get("pageNum")); +// // 迭代,产生图片数据流 +// for (int i = 0; i < pageNum; i++) { +// bytes = createSingleLineAndShapeChart((double[][]) (map.get("data" + i)), (String[]) (map.get("rowKeys" + i)), +// (String[]) (map.get("columnKeys" + i)), entity); +// list.add(bytes); +// } +// return list; +// } +// +// /** +// * 生成单个折线图数据流 +// * +// * @param data +// * @param rowKeys +// * @param columnKeys +// * @param entity +// * @return +// * @throws IOException +// */ +// public byte[] createSingleLineAndShapeChart(double[][] data, String[] rowKeys, String[] columnKeys, ChartEntity entity) throws IOException { +// CategoryDataset dataset = getBarData(data, rowKeys, columnKeys); +// JFreeChart chart = createTimeXYChar(dataset, entity); +// byte[] bytes = this.createImage(chart, entity); +// return bytes; +// } +// +// +// /** +// * 生成柱状图
+// * 1.解析数据
+// * 2.迭代数据,产出图片数据流,并添加到List
+// * +// * @param data 数据 +// * @param rowKeys 行 +// * @param columnKeys 列 +// * @param entity 图片配置对象 +// * @return 包含多个图片数据流的List +// * @throws IOException +// */ +// public ArrayList createStackedBarChart(double[][] data, String[] rowKeys, String[] columnKeys, ChartEntity entity) throws IOException { +// // 解析数据 +// ArrayList list = new ArrayList(); +// byte[] bytes = new byte[]{}; +// Map map = this.parseDataForBarPage(data, rowKeys, columnKeys); +// int pageNum = Integer.parseInt("" + map.get("pageNum")); +// // 迭代数据,产出图片数据流,并添加到List +// for (int i = 0; i < pageNum; i++) { +// bytes = createSingleStackedBarChart((double[][]) (map.get("data" + i)), (String[]) (map.get("rowKeys" + i)), +// (String[]) (map.get("columnKeys" + i)), entity); +// list.add(bytes); +// } +// return list; +// } +// +// /** +// * 解析生成柱状图分页数据 +// * +// * @param data +// * @param rowKeys +// * @param columnKeys +// * @return +// */ +// private Map parseDataForBarPage(double[][] data, String[] rowKeys, String[] columnKeys) { +// Map map = new HashMap(); +// +// double[][] pageData = null; +// String[] pageColumn = null; +// +// int sumColumnNum = columnKeys.length; // 总列数 +// int indexNum = Config.getInt("image.export.pagesize", 10);// 分页的列数 +// int pageNum = sumColumnNum % indexNum == 0 ? sumColumnNum / indexNum : sumColumnNum / indexNum + 1; // 分页数 +// int rowNum = rowKeys.length; +// +// // log.debug("data.length="+data.length+"sumColumnNum="+sumColumnNum+" indexNum="+indexNum+" pageNum="+pageNum+" rowNum="+rowNum+" "); +// +// // 解析传递过来的数据 +// for (int i = 0; i < pageNum; i++) { +// int columnNum = (sumColumnNum - i * indexNum) / indexNum > 0 ? indexNum : (sumColumnNum - i * indexNum) % indexNum;//当前页列数 +// pageData = new double[rowNum][columnNum]; +// // 取数据值 +// for (int j = 0; j < rowNum; j++) { +// pageColumn = new String[columnNum]; +// for (int k = 0; k < columnNum; k++) { +// pageData[j][k] = data[j][k + i * indexNum]; // 数据 +// } +// } +// // 取列值 +// for (int j = 0; j < columnNum; j++) { +// pageColumn[j] = columnKeys[j + i * indexNum]; // 列 +// } +// // 保存数据并返回 +// map.put("data" + i, pageData); +// map.put("rowKeys" + i, rowKeys); +// map.put("columnKeys" + i, pageColumn); +// } +// // 保存分页数 +// map.put("pageNum", pageNum); +// return map; +// } +// +// /** +// * 解析生成折线图分页数据 +// * +// * @param data +// * @param rowKeys +// * @param columnKeys +// * @return +// */ +// private Map parseDataForLinePage(double[][] data, String[] rowKeys, String[] columnKeys) { +// Map map = new HashMap(); +// +// double[][] pageData = null; +// String[] pageColumn = null; +// +// int sumColumnNum = columnKeys.length; // 总列数 +// int indexNum = Config.getInt("image.export.pagesize", 10);// 分页的列数 +// int pageNum = sumColumnNum % indexNum == 0 ? sumColumnNum / indexNum : sumColumnNum / indexNum + 1; // 分页数 +// int rowNum = rowKeys.length; +// +// // log.debug("data.length="+data.length+"sumColumnNum="+sumColumnNum+" indexNum="+indexNum+" pageNum="+pageNum+" rowNum="+rowNum+" "); +// +// // 解析传递过来的数据 +// for (int i = 0; i < pageNum; i++) { +// int columnNum = (sumColumnNum - i * indexNum) / indexNum > 0 ? indexNum : (sumColumnNum - i * indexNum) % indexNum;//当前页列数 +// pageData = new double[rowNum][columnNum]; +// // 取数据值 +// for (int j = 0; j < rowNum; j++) { +// pageColumn = new String[columnNum]; +// for (int k = 0; k < columnNum; k++) { +// pageData[j][k] = data[j][k + i * indexNum]; // 数据 +// } +// } +// // 取列值 +// for (int j = 0; j < columnNum; j++) { +// pageColumn[j] = columnKeys[j + i * indexNum]; // 列 +// } +// // 保存数据并返回 +// map.put("data" + i, pageData); +// map.put("rowKeys" + i, rowKeys); +// map.put("columnKeys" + i, pageColumn); +// } +// // 保存分页数 +// map.put("pageNum", pageNum); +// return map; +// } +// +// /** +// * 生成单个堆栈柱状图 +// * +// * @return 图片数据流 +// * @throws IOException +// */ +// public byte[] createSingleStackedBarChart(double[][] data, String[] rowKeys, String[] columnKeys, ChartEntity entity) throws IOException { +// CategoryDataset dataset = getBarData(data, rowKeys, columnKeys); +// JFreeChart chart = createStackedBarChart(dataset, entity); +// byte[] bytes = this.createImage(chart, entity); +// return bytes; +// } +// +// // 柱状图,折线图 数据集 +// private CategoryDataset getBarData(double[][] data, String[] rowKeys, +// String[] columnKeys) { +// return DatasetUtilities.createCategoryDataset(rowKeys, columnKeys, data); +// +// } +// +// /** +// * 判断文件夹是否存在,如果不存在则新建 +// * +// * @param chartPath +// */ +// private void isChartPathExist(String chartPath) { +// File file = new File(chartPath); +// if (!file.exists()) { +// file.mkdirs(); +// } +// } +// +// /** +// * 折线图 +// */ +// private JFreeChart createTimeXYChar(CategoryDataset xyDataset, ChartEntity entity) { +// +// JFreeChart chart = ChartFactory.createLineChart( +// entity.getTitle(), +// entity.getXname(), +// entity.getYname(), +// xyDataset, +// PlotOrientation.VERTICAL, +// true, +// true, +// false); +// +// chart.setTextAntiAlias(false); +// chart.setBackgroundPaint(Color.WHITE); +// +// CategoryPlot categoryplot = (CategoryPlot) chart.getPlot(); +// // 没有数据时显示 +// this.configNoData(chart, "没有查询到数据 !"); +// +// // x轴 // 分类轴网格是否可见 +// categoryplot.setDomainGridlinesVisible(true); +// // y轴 //数据轴网格是否可见 +// categoryplot.setRangeGridlinesVisible(true); +// +// categoryplot.setRangeGridlinePaint(Color.WHITE);// 虚线色彩 +// +// categoryplot.setDomainGridlinePaint(Color.WHITE);// 虚线色彩 +// +// categoryplot.setBackgroundPaint(Color.lightGray); +// +// +// // 配置字体 +// this.configFont(chart); +// +// // x轴设置 +// CategoryAxis domainAxis = categoryplot.getDomainAxis(); +// +// // 设置距离图片左端距离 +// domainAxis.setLowerMargin(0.0); +// // 设置距离图片右端距离 +// domainAxis.setUpperMargin(0.0); +// domainAxis.setTickLabelPaint(Color.BLUE); +// domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45); // 横轴上的label斜显示 +// +// NumberAxis numberaxis = (NumberAxis) categoryplot.getRangeAxis(); +// numberaxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); +// numberaxis.setAutoRangeIncludesZero(true); +// +// // 获得renderer 注意这里是下嗍造型到lineandshaperenderer!! +// LineAndShapeRenderer lineandshaperenderer = (LineAndShapeRenderer) categoryplot.getRenderer(); +// lineandshaperenderer.setBaseShapesVisible(true); // series 点(即数据点)可见 +// lineandshaperenderer.setBaseLinesVisible(true); // series 点(即数据点)间有连线可见 +// +// // 显示折点数据 +// lineandshaperenderer.setBaseItemLabelGenerator(new +// StandardCategoryItemLabelGenerator()); +// lineandshaperenderer.setBaseItemLabelsVisible(true); +// +// return chart; +// } +// +// /** +// * 堆栈柱状图 +// */ +// private JFreeChart createStackedBarChart(CategoryDataset dataset, ChartEntity entity) { +// +// JFreeChart chart = ChartFactory.createStackedBarChart3D( +// entity.getTitle(), +// entity.getXname(), +// entity.getYname(), +// dataset, +// PlotOrientation.VERTICAL, +// true, +// false, +// false); +// +// // 没有数据配置 +// this.configNoData(chart, "没有查询到数据 !"); +// +// // 配置字体 +// this.configFont(chart); +// +// // 配置 Renderer +// this.configBarRenderer(chart); +// +// // 其他配置 +// this.configOtherForBar(chart); +// +// return chart; +// } +// +// /** +// * 配置字体 +// * +// * @param chart JFreeChart 对象 +// */ +// private void configFont(JFreeChart chart) { +// // 配置字体 +// Font xfont = new Font("宋体", Font.PLAIN, 12);// X轴 +// Font yfont = new Font("宋体", Font.PLAIN, 12);// Y轴 +// Font kfont = new Font("宋体", Font.PLAIN, 12);// 底部 +// Font titleFont = new Font("隶书", Font.BOLD, 25); // 图片标题 +// CategoryPlot plot = chart.getCategoryPlot();// 图形的绘制结构对象 +// +// // 图片标题 +// chart.setTitle(new TextTitle(chart.getTitle().getText(), titleFont)); +// +// // 底部 +// chart.getLegend().setItemFont(kfont); +// +// // X 轴 +// CategoryAxis domainAxis = plot.getDomainAxis(); +// domainAxis.setLabelFont(xfont);// 轴标题 +// domainAxis.setTickLabelFont(xfont);// 轴数值 +// domainAxis.setTickLabelPaint(Color.BLUE); // 字体颜色 +// domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45); // 横轴上的label斜显示 +// +// // Y 轴 +// ValueAxis rangeAxis = plot.getRangeAxis(); +// rangeAxis.setLabelFont(yfont); +// rangeAxis.setLabelPaint(Color.BLUE); // 字体颜色 +// rangeAxis.setTickLabelFont(yfont); +// +// } +// +// /** +// * 配置柱状图 +// * +// * @param chart +// */ +// private void configBarRenderer(JFreeChart chart) { +// +// CategoryPlot categoryplot = (CategoryPlot) chart.getPlot(); +// // 自定义显示柱子上的总值 +// ExtendedStackedBarRenderer extendedstackedbarrenderer = new ExtendedStackedBarRenderer(); +// extendedstackedbarrenderer.setBaseItemLabelsVisible(true); +// extendedstackedbarrenderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator()); +// extendedstackedbarrenderer.setBaseToolTipGenerator(new StandardCategoryToolTipGenerator()); +// categoryplot.setRenderer(extendedstackedbarrenderer); +// +// BarRenderer barrenderer = (BarRenderer) categoryplot.getRenderer(); +// barrenderer.setDrawBarOutline(false); +// barrenderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator()); +// barrenderer.setBaseItemLabelsVisible(true); +// barrenderer.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.CENTER)); +// barrenderer.setBaseNegativeItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.CENTER)); +// +// // 柱子显示数值 +// // barrenderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator("{2}",new DecimalFormat("0.0%"))); +// // barrenderer.setItemLabelGenerator(new StandardCategoryItemLabelGenerator()); +// barrenderer.setItemLabelFont(new Font("Arial Unicode MS", Font.PLAIN, 9)); +// barrenderer.setItemLabelsVisible(true); +// +// // 如果数值没有显示空间,设置显示格式 +// // ItemLabelPosition itemLabelPositionFallback=new ItemLabelPosition( +// // ItemLabelAnchor.OUTSIDE12,TextAnchor.BASELINE_LEFT, +// // TextAnchor.HALF_ASCENT_LEFT,0D); +// // barrenderer.setPositiveItemLabelPositionFallback(itemLabelPositionFallback); +// // barrenderer.setNegativeItemLabelPositionFallback(itemLabelPositionFallback); +// +// categoryplot.setRenderer(barrenderer); +// } +// +// /** +// * 配置没有数据时的显示信息 +// * +// * @param chart +// */ +// private void configNoData(JFreeChart chart, String message) { +// CategoryPlot categoryplot = (CategoryPlot) chart.getPlot(); +// // 没有数据时的显示 +// categoryplot.setNoDataMessage(message); +// categoryplot.setNoDataMessageFont(new Font("黑体", Font.BOLD, 25)); +// } +// +// /** +// * 其他配置 +// * +// * @param chart +// */ +// private void configOtherForBar(JFreeChart chart) { +// +// chart.setTextAntiAlias(false); // 图例字体清晰 +// +// chart.setBackgroundPaint(Color.WHITE); // 背景颜色 +// +// CategoryPlot plot = chart.getCategoryPlot();// 图形的绘制结构对象 +// NumberAxis numberaxis = (NumberAxis) plot.getRangeAxis(); +// numberaxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); +// numberaxis.setAutoRangeIncludesZero(true); +// } +// +// /** +// * 创建图片的数据流 +// * +// * @param chart +// * @param entity 图片配置对象 +// * @return 图片数据流 +// * @throws IOException +// */ +// private byte[] createImage(JFreeChart chart, ChartEntity entity) throws IOException { +// return ChartUtilities.encodeAsPNG(chart.createBufferedImage(entity.getWidth(), entity.getHeight())); +// } +// +// /** +// * 创建图片文件到硬盘 +// * +// * @param chart +// * @param entity +// * @throws IOException +// */ +// private void createImageFile(JFreeChart chart, ChartEntity entity) throws IOException { +// FileOutputStream fos_jpg = null; +// try { +// isChartPathExist(tempImgPath); +// String chartName = tempImgPath + entity.getFileName(); +// fos_jpg = new FileOutputStream(chartName); +// ChartUtilities.writeChartAsJPEG(fos_jpg, chart, entity.getWidth(), entity.getHeight()); +// } catch (Exception e) { +// e.printStackTrace(); +// } finally { +// try { +// fos_jpg.close(); +// } catch (Exception e) { +// e.printStackTrace(); +// } +// } +// } +} diff --git a/hzims-service/operational/src/main/java/com/hnac/hzims/operational/util/WordUtils.java b/hzims-service/operational/src/main/java/com/hnac/hzims/operational/util/WordUtils.java index 2e17bfb..306ab29 100644 --- a/hzims-service/operational/src/main/java/com/hnac/hzims/operational/util/WordUtils.java +++ b/hzims-service/operational/src/main/java/com/hnac/hzims/operational/util/WordUtils.java @@ -1,12 +1,19 @@ package com.hnac.hzims.operational.util; + +import cn.afterturn.easypoi.word.WordExportUtil; +import cn.hutool.core.lang.Assert; import com.hnac.hzims.operational.util.pojo.HttpResponse; import freemarker.cache.StringTemplateLoader; import freemarker.template.Configuration; +import org.apache.poi.xwpf.usermodel.XWPFDocument; import javax.servlet.http.HttpServletResponse; +import java.io.File; +import java.io.FileOutputStream; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; +import java.util.Map; /** * world文档工具类 @@ -39,4 +46,41 @@ public abstract class WordUtils { fileName = URLEncoder.encode(fileName, "UTF-8"); response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".doc"); } + + /** + * 导出word + *

第一步生成替换后的word文件,只支持docx

+ *

第二步下载生成的文件

+ *

第三步删除生成的临时文件

+ * 模版变量中变量格式:{{foo}} + * + * @param templatePath word模板地址 + * @param temDir 生成临时文件存放地址 + * @param fileName 文件名 + * @param params 替换的参数 + */ + public static void exportWord(String templatePath, String temDir, String fileName, Map params) { + Assert.notNull(templatePath, "模板路径不能为空"); + Assert.notNull(temDir, "临时文件路径不能为空"); + Assert.notNull(fileName, "导出文件名不能为空"); + Assert.isTrue(fileName.endsWith(".docx"), "word导出请使用docx格式"); + if (!temDir.endsWith("/")) { + temDir = temDir + File.separator; + } + File dir = new File(temDir); + if (!dir.exists()) { + dir.mkdirs(); + } + try { + XWPFDocument doc = WordExportUtil.exportWord07(templatePath, params); + String tmpPath = temDir + fileName; + FileOutputStream fos = new FileOutputStream(tmpPath); + doc.write(fos); + fos.flush(); + fos.close(); + } catch (Exception e) { + e.printStackTrace(); + } + } + }