Commit 9578bb05 authored by shulidong's avatar shulidong

报告生成基础代码及获取hbase最后一条数据

parent 493d231f
......@@ -231,6 +231,7 @@
<artifactId>jcommon</artifactId>
<version>1.0.24</version>
</dependency>
<dependency>
<groupId>org.jfree</groupId>
<artifactId>jfreechart</artifactId>
......
......@@ -59,6 +59,11 @@ public class DataPower implements Serializable {
*/
private List<String> value = new ArrayList<>();
private List<String> singleType = new ArrayList<>();
/**
* 量程
*/
private Float measuer;
}
}
package cn.wise.sc.energy.power.plant.business.constant;
/**
* @author neo.shu
* @since 2020/10/6 09:43
*/
public class Constance {
/**
* 摄氏度符号
*/
public static final String CELSIUS = new String(new int[]{0x2103}, 0, 1);
/**
* 目前仅在tableUtil里面插入表格内容时处理了。表示换行
*/
public static final String RETURN = "\n";
public static final String SPLIT = ":";
}
package cn.wise.sc.energy.power.plant.business.controller;
import cn.wise.sc.energy.power.plant.business.domain.vo.AlertInfoVo;
import cn.wise.sc.energy.power.plant.business.utils.poi.DocxService;
import cn.wise.sc.energy.power.plant.common.core.bean.BaseResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.util.List;
/**
* @description: 阈值更新记录
......@@ -17,8 +21,19 @@ import java.util.List;
@RequestMapping("alertinfo/")
public class AlertInfoController {
@GetMapping
@Autowired
DocxService docxService;
@GetMapping("/test")
public BaseResponse<List<AlertInfoVo>> list(){
try {
docxService.fillDocx();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
package cn.wise.sc.energy.power.plant.business.controller;
import lombok.extern.slf4j.Slf4j;
import cn.wise.sc.energy.power.plant.business.domain.AbstractEntity;
import cn.wise.sc.energy.power.plant.business.domain.vo.EntityVo;
import cn.wise.sc.energy.power.plant.business.service.IBaseService;
import cn.wise.sc.energy.power.plant.common.core.bean.EntityQuery;
import cn.wise.sc.energy.power.plant.common.core.bean.BaseResponse;
import cn.wise.sc.energy.power.plant.common.core.bean.EntityQuery;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
......
......@@ -9,9 +9,12 @@ import cn.wise.sc.energy.power.plant.business.jna.C2TreeAnalysis;
import cn.wise.sc.energy.power.plant.business.repository.BtreeInfoConfigRepository;
import cn.wise.sc.energy.power.plant.business.utils.BeanUtilsExt;
import cn.wise.sc.energy.power.plant.business.utils.Utils;
import cn.wise.sc.energy.power.plant.business.utils.dfs.FastDFSUtils;
import cn.wise.sc.energy.power.plant.business.utils.poi.DocxService;
import cn.wise.sc.energy.power.plant.common.core.bean.BaseResponse;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBucket;
import org.redisson.api.RList;
import org.redisson.api.RedissonClient;
......@@ -24,6 +27,9 @@ import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
......@@ -37,6 +43,7 @@ import java.util.concurrent.TimeUnit;
@CrossOrigin
@RestController
@RequestMapping("btreeinspec/")
@Slf4j
public class BtreeInspectionController {
@Autowired
......@@ -161,4 +168,30 @@ public class BtreeInspectionController {
}
@Autowired
protected HttpServletResponse response;
@Autowired
protected HttpServletRequest request;
@Autowired
DocxService docxService;
@PostMapping("/reportDownload")
public BaseResponse fileDownload() {
OutputStream out = null;
try {
response.setHeader("Content-Disposition", "attachment;filename=" + "demo1" + ".docx");
response.setContentType("application/force-download");
out = response.getOutputStream();
byte[] by = docxService.fillDocx();
out.write(by);
out.close();
return BaseResponse.okMsg("成功");
} catch (Exception e) {
log.error(e.toString());
}
return BaseResponse.errorMsg("失败");
}
}
package cn.wise.sc.energy.power.plant.business.controller;
import cn.wise.sc.energy.power.plant.business.bean.DataPower;
import cn.wise.sc.energy.power.plant.business.domain.BtreeInfoConfig;
import cn.wise.sc.energy.power.plant.business.domain.CharacterParamInfo;
import cn.wise.sc.energy.power.plant.business.domain.TendencyQuery;
import cn.wise.sc.energy.power.plant.business.domain.vo.EntityVo;
import cn.wise.sc.energy.power.plant.business.repository.CharacterParamRepository;
import cn.wise.sc.energy.power.plant.business.service.ICharacterParamService;
import cn.wise.sc.energy.power.plant.business.utils.BeanUtilsExt;
import cn.wise.sc.energy.power.plant.common.core.bean.BaseResponse;
import com.spring4all.spring.boot.starter.hbase.api.HbaseTemplate;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
......@@ -22,10 +27,7 @@ import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.validation.constraints.NotEmpty;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
......@@ -44,6 +46,9 @@ public class CharacterParamController {
final
ICharacterParamService iCharacterParamService;
@Autowired
CharacterParamRepository characterParamRepository;
final
HbaseTemplate hbaseTemplate;
......@@ -93,4 +98,24 @@ public class CharacterParamController {
return BaseResponse.okData(iCharacterParamService.getFrequencyByUpload(file));
}
@ApiOperation("更新阈值")
@PostMapping("/configUpdate")
public BaseResponse<Boolean> interaction(@RequestBody CharacterParamInfo info) {
CharacterParamInfo config;
if (info.getKksCode() == null) {
config = characterParamRepository.save(info);
} else {
config = characterParamRepository.getOne(info.getKksCode());
BeanUtils.copyProperties(info, config, BeanUtilsExt.getNullPropertyNames(info));
config = characterParamRepository.save(config);
}
if (config.getKksCode() != null) {
return BaseResponse.okData(true);
} else {
return BaseResponse.okData(false);
}
}
}
......@@ -9,6 +9,7 @@ import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.constraints.NotEmpty;
import java.util.List;
......
package cn.wise.sc.energy.power.plant.business.controller;
import cn.hutool.core.util.StrUtil;
import cn.wise.sc.energy.power.plant.business.domain.CaseAnalysisInfo;
import cn.wise.sc.energy.power.plant.business.domain.CharacterParamInfo;
import cn.wise.sc.energy.power.plant.business.domain.EventInfo;
import cn.wise.sc.energy.power.plant.business.domain.PageQuery;
import cn.wise.sc.energy.power.plant.business.domain.vo.EntityVo;
import cn.wise.sc.energy.power.plant.business.repository.EventInfoRepository;
import cn.wise.sc.energy.power.plant.business.service.IEventInfoService;
import cn.wise.sc.energy.power.plant.business.utils.BeanUtilsExt;
import cn.wise.sc.energy.power.plant.common.core.bean.BaseResponse;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
......@@ -18,12 +30,15 @@ import java.util.List;
**/
@CrossOrigin
@RestController
@RequestMapping("event/info/")
@RequestMapping("eventinfo/")
public class EventInfoController {
final
IEventInfoService iEventInfoService;
@Autowired
EventInfoRepository repository;
public EventInfoController(IEventInfoService iEventInfoService) {
this.iEventInfoService = iEventInfoService;
}
......@@ -38,4 +53,30 @@ public class EventInfoController {
}
}
@PostMapping("/page")
public BaseResponse<Page<EventInfo>> page(@RequestBody PageQuery page) {
return iEventInfoService.page(page);
}
@ApiOperation("更新事件状态")
@PostMapping("/configUpdate")
public BaseResponse<Boolean> interaction(@RequestBody EventInfo info) {
EventInfo config;
if (info.getId() == null) {
config = repository.save(info);
} else {
config = repository.getOne(info.getId());
BeanUtils.copyProperties(info, config, BeanUtilsExt.getNullPropertyNames(info));
config = repository.save(config);
}
if (config.getId() != null) {
return BaseResponse.okData(true);
} else {
return BaseResponse.okData(false);
}
}
}
......@@ -8,6 +8,7 @@ import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.constraints.NotEmpty;
import java.util.List;
......
package cn.wise.sc.energy.power.plant.business.dataware;
import lombok.Builder;
import lombok.Data;
/**
* @author neo.shu
* @since 2020/9/29 22:39
*/
@Data
@Builder
public class PointDataFromHbase {
private String tag;
private long timeStamp;
private String value;
}
package cn.wise.sc.energy.power.plant.business.dataware;
import com.spring4all.spring.boot.starter.hbase.api.RowMapper;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.client.Result;
/**
* @author: neo.shu
* @create: 2020-09-29 22:38
**/
public class PointRowKeyMapper implements RowMapper<PointDataFromHbase> {
@Override
public PointDataFromHbase mapRow(Result result, int rowNum) {
Cell cell = (result.rawCells())[0];
//System.out.println("查询到hbase时间戳==============="+cell.getTimestamp());
return PointDataFromHbase.builder().timeStamp(cell.getTimestamp())
.build();
}
}
package cn.wise.sc.energy.power.plant.business.domain;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import lombok.Data;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.time.LocalDateTime;
import java.time.LocalTime;
/**
* @author neo.shu
* @since 2020/9/28 14:33
*/
@Data
@Entity
@Table(name = "autoInspection")
public class AutoInspection {
private String id;
@Id
private Integer recordid;
private LocalDateTime btreetime;
private Integer grade;
private String plantid;
private String deviceid;
private String typed;
private String unitname;
private String btreename;
private Integer result;
private String diagnosis;
public static void main(String[] args) {
String a = "{\"name\": \"励端\", \"RunoutX\": {\"1X\": 1.47635805606842, \"2X\": 0.04492176324129105, \"3X\": 1.47635805606842}, \"RunoutY\": {\"1X\": 1.47635805606842, \"2X\": 0.04492176324129105, \"3X\": 1.47635805606842}, \"VibrateX\": {\"1X\": 1.47635805606842, \"2X\": 0.04492176324129105, \"3X\": 1.47635805606842}, \"VibrateY\": {\"1X\": 1.47635805606842, \"2X\": 0.04492176324129105, \"3X\": 1.47635805606842}, \"diagnosis\": \"机械不存在故障\"}";
JSONObject jsonObject = JSON.parseObject(a);
jsonObject.get("");
}
}
......@@ -149,6 +149,14 @@ public class CharacterParamInfo extends AbstractEntity<String> implements Serial
@Column(name = "hasderiveparam")
private Integer hasDeriveParam;
private Integer measuringrangerulevalid;
private Float measuringrangeruleminvalue;
private Float measuringrangerulemaxvalue;
private Integer measuringrangeruleexclude;
@Override
public String getId() {
return getKksCode();
......
......@@ -10,6 +10,7 @@ import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.time.LocalDateTime;
/**
* @description: 事件记录
......@@ -35,7 +36,7 @@ public class EventInfo extends AbstractEntity<Long> {
* 记录时间
*/
@Column(name = "valuetime")
private long valueTime;
private LocalDateTime valueTime;
/**
* 监测特征所属电站的标识
......@@ -110,4 +111,9 @@ public class EventInfo extends AbstractEntity<Long> {
@Column(name = "eventinfo")
private Integer eventInfo;
/**
* 联表查询测点名称
*/
private String cpname;
}
......@@ -24,7 +24,8 @@ public class PageQuery implements Serializable {
private String plantId;
private String startTime;
private String endTime;
private String unitcodeid;
private Integer alertstat;
private String order;
}
......@@ -73,7 +73,8 @@ public class RowKeyMapper implements RowMapper<Oscillogram> {
try {
oscillogram.setStart(Long.parseLong(startTime));
} catch (NumberFormatException ex) {
throw new RuntimeException("HBase这个波形图开始时间不为0");
oscillogram.setStart(System.currentTimeMillis());
//throw new RuntimeException("HBase这个波形图开始时间不为0");
}
return oscillogram;
}
......
......@@ -109,9 +109,18 @@ public class CharacterParamInfoVo extends EntityVo{
private Integer hasDeriveParam;
private List<CharacterParamInfoVo> child;
/**
* 图形
*/
private String function;
private Integer measuringrangerulevalid;
private Float measuringrangeruleminvalue;
private Float measuringrangerulemaxvalue;
private Integer measuringrangeruleexclude;
}
package cn.wise.sc.energy.power.plant.business.opentsdb;
import cn.wise.sc.energy.power.plant.business.config.MyApplicationContextAware;
import cn.wise.sc.energy.power.plant.business.dataware.PointDataFromHbase;
import cn.wise.sc.energy.power.plant.business.dataware.PointRowKeyMapper;
import cn.wise.sc.energy.power.plant.business.domain.CharacterParamInfo;
import cn.wise.sc.energy.power.plant.business.domain.Oscillogram;
import cn.wise.sc.energy.power.plant.business.domain.RowKeyMapper;
import cn.wise.sc.energy.power.plant.business.domain.vo.CharacterParamInfoVo;
import cn.wise.sc.energy.power.plant.business.opentsdb.bean.PutRequestExt;
import cn.wise.sc.energy.power.plant.business.opentsdb.bean.QueryRequestExt;
import cn.wise.sc.energy.power.plant.business.utils.OkHttpClientUtil;
import com.alibaba.fastjson.JSON;
import com.spring4all.spring.boot.starter.hbase.api.HbaseTemplate;
import net.opentsdb.client.api.Endpoint;
import net.opentsdb.client.api.annotation.request.CreateAnnotationRequest;
import net.opentsdb.client.api.annotation.request.DeleteAnnotationRequest;
......@@ -33,6 +39,7 @@ import net.opentsdb.client.bean.LastDataPointQuery;
import net.opentsdb.client.bean.QueryResult;
import net.opentsdb.client.util.JsonUtil;
import okhttp3.Response;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
......@@ -211,14 +218,53 @@ public class OpentsdbOkHttpClient {
.build();
}
public static Long queryLast(List<CharacterParamInfoVo> characterParamInfoVos) {
QueryLastRequest queryLastRequest = new QueryLastRequest();
/* QueryLastRequest queryLastRequest = new QueryLastRequest();
List<LastDataPointQuery> list = new ArrayList<>();
characterParamInfoVos.stream().forEach(info -> {
list.add(LastDataPointQuery.builder().metric(info.getKksCode()).build());
});
queryLastRequest.setQueries(list);
QueryLastResponse queryLastResponse;
try {
queryLastResponse = OpentsdbOkHttpClient.queryLast(queryLastRequest);
List<LastDataPoint> results = queryLastResponse.getResults();
final Long[] latestTime = {0L};
if (!CollectionUtils.isEmpty(results)) {
results.stream().forEach(result -> {
if (latestTime[0] < result.getTimestamp()) {
latestTime[0] = result.getTimestamp();
}
});
return latestTime[0];
} else {
return System.currentTimeMillis();
}
} catch (IOException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
}*/
HbaseTemplate hbaseTemplate = (HbaseTemplate) MyApplicationContextAware.getApplicationContext().getBean("hbaseTemplate");
try {
PointDataFromHbase pointDataFromHbase = hbaseTemplate.get("thermalpower-plant-point-data", characterParamInfoVos.get(0).getKksCode(), new PointRowKeyMapper());
return pointDataFromHbase.getTimeStamp();
} catch (Exception e) {
return System.currentTimeMillis();
}
}
public static Long queryLastBykks(List<String> kkscodes) {
/*QueryLastRequest queryLastRequest = new QueryLastRequest();
List<LastDataPointQuery> list = new ArrayList<>();
kkscodes.stream().forEach(value -> {
list.add(LastDataPointQuery.builder().metric(value).build());
});
queryLastRequest.setQueries(list);
QueryLastResponse queryLastResponse;
try {
queryLastResponse = OpentsdbOkHttpClient.queryLast(queryLastRequest);
List<LastDataPoint> results = queryLastResponse.getResults();
......@@ -239,7 +285,16 @@ public class OpentsdbOkHttpClient {
} catch (URISyntaxException e) {
e.printStackTrace();
}
return 0L;
return 0L;*/
HbaseTemplate hbaseTemplate = (HbaseTemplate) MyApplicationContextAware.getApplicationContext().getBean("hbaseTemplate");
try {
PointDataFromHbase pointDataFromHbase = hbaseTemplate.get("thermalpower-plant-point-data", kkscodes.get(0), new PointRowKeyMapper());
return pointDataFromHbase.getTimeStamp();
} catch (Exception e) {
return System.currentTimeMillis();
}
}
/**
......
package cn.wise.sc.energy.power.plant.business.poi;
import java.util.ArrayList;
import java.util.HashMap;
import cn.afterturn.easypoi.entity.ImageEntity;
/**
* @author 何昌杰
*/
public class WordDemo1 {
public static void main(String[] args) {
HashMap<String, Object> map = new HashMap<>(4);
long startTime = System.currentTimeMillis();
//模拟饼状图数据
HashMap<String, Integer> datas = new HashMap<>(3);
datas.put("一号",10);
datas.put("二号",20);
datas.put("三号",40);
ImageEntity imageEntity = JfreeUtil.pieChart("测试",datas, 500, 300);
map.put("picture", imageEntity);
//模拟其它普通数据
map.put("username", "张三");
map.put("date", "2019-10-10");
map.put("desc", "测试");
map.put("boo", true);
//模拟表格数据
ArrayList<HashMap<String, String>> list = new ArrayList<>(2);
HashMap<String, String> temp = new HashMap<>(3);
temp.put("sn","1");
temp.put("name","第一个人");
temp.put("age","23");
list.add(temp);
for (int i = 0; i < 100; i++) {
temp = new HashMap<>(3);
temp.put("sn","2");
temp.put("name","第二个人");
temp.put("age","24");
list.add(temp);
}
map.put("personlist",list);
//word模板相对路径、word生成路径、word生成的文件名称、数据源
WordUtil.exportWord("C:\\Users\\admin\\Desktop\\template\\demo1.docx", "D:/", "生成文件.docx", map);
System.out.println(System.currentTimeMillis()-startTime);
}
}
\ No newline at end of file
package cn.wise.sc.energy.power.plant.business.repository;
import cn.wise.sc.energy.power.plant.business.domain.AlertInfo;
import cn.wise.sc.energy.power.plant.business.domain.AutoInspection;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* @description: 阈值更新记录仓储
* @author: neo.shu
* @create: 2020-10-06 14:41
**/
@Repository
public interface AutoInspectionRepository extends
JpaRepository<AutoInspection, Integer>,
JpaSpecificationExecutor<AutoInspection> {
List<AutoInspection> findAutoInspectionsById(String id);
}
......@@ -25,6 +25,6 @@ public interface EventInfoRepository extends
* @return list
*/
@Query(value = "SELECT COUNT(e.alertStat) as count, e.alertStat, e.deviceId FROM EventInfo as e" +
" where e.alertStat > 1 and e.alertStat < 5 GROUP BY e.alertStat,e.deviceId")
" where e.alertStat > 1 and e.alertStat < 6 GROUP BY e.alertStat,e.deviceId")
List<Object[]> countAlert();
}
......@@ -48,10 +48,10 @@ public class JWTFilter extends BasicAuthenticationFilter {
final String token = this.getToken(request);
//设置websocket 子协议头
response.setHeader("Sec-WebSocket-Protocol",request.getHeader("Sec-WebSocket-Protocol"));
/*if(true){
if(true){
filterChain.doFilter(request, response);
return;
}*/
}
if(request.getServletPath().contains("/login")||request.getServletPath().contains("/plantInfo/allPlantInfo")){
filterChain.doFilter(request, response);
return;
......
package cn.wise.sc.energy.power.plant.business.service;
import cn.wise.sc.energy.power.plant.business.domain.EventInfo;
import cn.wise.sc.energy.power.plant.business.domain.PageQuery;
import cn.wise.sc.energy.power.plant.business.domain.vo.EntityVo;
import cn.wise.sc.energy.power.plant.business.service.impl.EventInfoServiceImpl;
import cn.wise.sc.energy.power.plant.common.core.bean.BaseResponse;
import org.springframework.data.domain.Page;
import java.util.List;
/**
......@@ -31,4 +35,6 @@ public interface IEventInfoService extends IBaseService<Long, EventInfo> {
* @return 报警记录
*/
List<EventInfo> getList(List<String> kKSCodes);
BaseResponse<Page<EventInfo>> page(PageQuery page);
}
......@@ -30,6 +30,7 @@ import lombok.extern.slf4j.Slf4j;
import net.opentsdb.client.api.query.response.QueryResponse;
import net.opentsdb.client.bean.Aggregator;
import net.opentsdb.client.bean.QueryResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Example;
......@@ -362,10 +363,11 @@ public class CharacterParamServiceImpl extends BaseServiceImpl<String, Character
}
return in;
});
//如果时间传0 默认取最后一条数据向前推1h
//如果时间传0 查最后一条 往前推30min
if (timeModelQuery.getStart() == 0 || timeModelQuery.getEnd() == 0) {
timeModelQuery.setStart(1597456800000L);
timeModelQuery.setEnd(1597460400000L);
long lastTime = OpentsdbOkHttpClient.queryLastBykks(keys);
timeModelQuery.setStart(lastTime-1*3600*1000);
timeModelQuery.setEnd(lastTime);
// QueryLastRequest queryLastRequest = new QueryLastRequest();
// LastDataPointQuery lastDataPointQuery = new LastDataPointQuery();
......@@ -455,8 +457,9 @@ public class CharacterParamServiceImpl extends BaseServiceImpl<String, Character
System.out.println("============rowKey=============");
for (String kKSCode : kksCodes) {
System.out.println(getRowKey(kKSCode));
Oscillogram oscillogram = hbaseTemplate.get(tableName, getRowKey(kKSCode),
Oscillogram oscillogram = hbaseTemplate.get(tableName, kKSCode.toLowerCase(),
new RowKeyMapper());
if (oscillogram != null) {
oscillogramList.add(oscillogram);
}
......@@ -671,8 +674,14 @@ public class CharacterParamServiceImpl extends BaseServiceImpl<String, Character
String str = "时间\t1F定子上下线棒层间温度1A\t1F定子上下线棒层间温度2A";
String[] split = str.split("\t");
System.out.println(split[1]);
}
double a = 23;
double b = Double.parseDouble(a + "" + "02");
String substring = "C0A00101MKA12CY614R".substring("C0A00101MKA12CY614R".length() - 1);
System.out.println( StrUtil.swapCase(substring + "C0A00101MKA12CY614R"));
System.out.println("C0A00101MKA12CY614R".toLowerCase());
System.out.println(b);
}
private DataPower buildDataPower(List<QueryResult> results,
List<CharacterParamInfo> characterParamInfos) {
......@@ -721,6 +730,8 @@ public class CharacterParamServiceImpl extends BaseServiceImpl<String, Character
return StrUtil.swapCase(substring + kKSCode);
}
/**
* 拼装报警点
*
......
package cn.wise.sc.energy.power.plant.business.service.impl;
import cn.wise.sc.energy.power.plant.business.domain.CaseAnalysisInfo;
import cn.wise.sc.energy.power.plant.business.domain.DeviceInfo;
import cn.wise.sc.energy.power.plant.business.domain.EventInfo;
import cn.wise.sc.energy.power.plant.business.domain.PageQuery;
import cn.wise.sc.energy.power.plant.business.domain.vo.EntityVo;
import cn.wise.sc.energy.power.plant.business.repository.DeviceInfoRepository;
import cn.wise.sc.energy.power.plant.business.repository.EventInfoRepository;
import cn.wise.sc.energy.power.plant.business.service.IEventInfoService;
import cn.wise.sc.energy.power.plant.common.core.bean.BaseResponse;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
/**
......@@ -43,17 +55,17 @@ public class EventInfoServiceImpl extends BaseServiceImpl<Long, EventInfo> imple
List<Object[]> objects = eventInfoRepository.countAlert();
List<AlertCount> rts = new ArrayList<>();
Map<String,AlertCount> tendencyAlertMap =new HashMap<>();
for (Object[] objs : objects) {
//countAlert()查询2个字段 count()、alertState
if (objs.length != 2) {
/* if (objs.length != 2) {
continue;
}
}*/
Long count = (long) objs[0];
Integer state = (int) objs[1];
String deviceId = (String) objs[2];
Optional<DeviceInfo> byId = deviceInfoRepository.findById(deviceId);
if (byId.isPresent()) {
if (!byId.isPresent()) {
continue;
}
String deviceName = byId.get().getDeviceName();
......@@ -62,12 +74,17 @@ public class EventInfoServiceImpl extends BaseServiceImpl<Long, EventInfo> imple
alertCount = new AlertCount("preAlert", deviceName, count);
} else if (state == 3) {
alertCount = new AlertCount("tallAlert", deviceName, count);
} else {
} else if(state==4){
alertCount = new AlertCount("tooTallAlert", deviceName, count);
}else{
//趋势报警 5,6加和
alertCount = tendencyAlertMap.getOrDefault(deviceName, new AlertCount("tendencyAlert"));
alertCount.setCount(alertCount.getCount() + count);
alertCount.setDeviceName(deviceName);
tendencyAlertMap.put(deviceName, alertCount);
}
rts.add(alertCount);
}
return rts;
}
......@@ -106,7 +123,34 @@ public class EventInfoServiceImpl extends BaseServiceImpl<Long, EventInfo> imple
});
}
@Override
public BaseResponse<Page<EventInfo>> page(PageQuery page) {
Sort sort = Sort.by(Sort.Direction.DESC, "valueTime");
if (page.getOrder() != null && !page.getOrder().trim().equals("")) {
sort = Sort.by(Sort.Direction.DESC, page.getOrder());
}
Pageable pages = PageRequest.of(page.getPageNo(), page.getPageSize(), sort);
Page<EventInfo> infoPage;
Specification<EventInfo> specification = (root, query, cb) -> {
List<Predicate> list = new ArrayList<Predicate>();
//搜索
if (!StringUtils.isEmpty(page.getUnitcodeid())) {
list.add(cb.equal(root.get("unitCodeId").as(String.class), page.getUnitcodeid()));
}
//搜索
if (page.getAlertstat()!=null) {
list.add(cb.equal(root.get("alertStat").as(Integer.class), page.getAlertstat()));
}
return cb.and(list.toArray(new Predicate[list.size()]));
};
infoPage = eventInfoRepository.findAll(specification, pages);
return BaseResponse.okData(infoPage);
}
@Data
@NoArgsConstructor
public static class AlertCount {
public AlertCount(String alertLevel, String deviceName, Long count) {
this.alertLevel = alertLevel;
......@@ -114,6 +158,9 @@ public class EventInfoServiceImpl extends BaseServiceImpl<Long, EventInfo> imple
this.count = count;
}
public AlertCount(String alertLevel) {
this.alertLevel = alertLevel;
}
/**
* 报警级别
*/
......@@ -127,6 +174,6 @@ public class EventInfoServiceImpl extends BaseServiceImpl<Long, EventInfo> imple
/**
* 对应报警次数
*/
private Long count;
private Long count=0L;
}
}
......@@ -57,7 +57,7 @@ public class HydrogeSystem1Task extends ScheduleTask {
//向每个webSocket推送系统实时数据
for (String deviceId : groupMap.keySet()) {
List<CharacterParamInfoVo> characterParamInfoVos = taskCacheDataService.cacheHydrogeCha(deviceId);
Map<String, String> KKsCodes = characterParamInfoVos.stream().filter(item -> IS_CONTAINS(item.getCpName(), new String[]{"汽端发电机冷氢温度"})).collect(Collectors.toMap(CharacterParamInfoVo::getKksCode, CharacterParamInfoVo::getCpName));
Map<String, String> KKsCodes = characterParamInfoVos.stream().filter(item -> IS_CONTAINS(item.getCpName(), new String[]{"汽端冷氢温度"})).collect(Collectors.toMap(CharacterParamInfoVo::getKksCode, CharacterParamInfoVo::getCpName));
Long lastTime = OpentsdbOkHttpClient.queryLast(characterParamInfoVos);
QueryResponse response = iCharacterParamService
......@@ -75,7 +75,7 @@ public class HydrogeSystem1Task extends ScheduleTask {
finalList.add(item.toString());
});
powerPoints.setValue(finalList);
if (KKsCodes.get(queryResult.getMetric()).contains("汽端发电机冷氢温度")) {
if (KKsCodes.get(queryResult.getMetric()).contains("汽端冷氢温度")) {
DataPower dataPower = map.getOrDefault("rightBottom", new DataPower());
dataPower.setXAxis(xAxis);
dataPower.getDataList().add(powerPoints);
......
......@@ -51,7 +51,7 @@ public class HydrogeSystem3Task extends ScheduleTask {
}
//给每个deviceid分组,然后统一查询,进行推送
Map<String, List<Map.Entry<String, String>>> groupMap = deviceMap.entrySet().stream().collect(Collectors.groupingBy(c -> c.getValue()));
String[] measure_points = new String[]{"发电机机内氢压", "机内氢气湿度", "漏氢含量"};
String[] measure_points = new String[]{"机内氢压", "机内氢气湿度", "在线漏氢"};
//向每个webSocket推送系统实时数据
for (String deviceId : groupMap.keySet()) {
List<CharacterParamInfoVo> characterParamInfoVos = taskCacheDataService.cacheHydrogeCha(deviceId);
......@@ -78,7 +78,7 @@ public class HydrogeSystem3Task extends ScheduleTask {
finalList.add(item.toString());
});
powerPoints.setValue(finalList);
if (KKsCodes.get(queryResult.getMetric()).contains("发电机机内氢压")) {
if (KKsCodes.get(queryResult.getMetric()).contains("机内氢压")) {
//左上图
DataPower dataPower = map.getOrDefault("leftTop",new DataPower());
dataPower.setXAxis(xAxis);
......@@ -91,7 +91,7 @@ public class HydrogeSystem3Task extends ScheduleTask {
dataPower.getDataList().add(powerPoints);
map.putIfAbsent("leftBottom", dataPower);
}
if (KKsCodes.get(queryResult.getMetric()).contains("漏氢含量")) {
if (KKsCodes.get(queryResult.getMetric()).contains("在线漏氢")) {
DataPower dataPower = map.getOrDefault("rightTop",new DataPower());
dataPower.setXAxis(xAxis);
dataPower.getDataList().add(powerPoints);
......
......@@ -3,10 +3,12 @@ package cn.wise.sc.energy.power.plant.business.task;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.wise.sc.energy.power.plant.business.bean.DataPower;
import cn.wise.sc.energy.power.plant.business.domain.CharacterParamInfo;
import cn.wise.sc.energy.power.plant.business.domain.vo.CharacterParamInfoVo;
import cn.wise.sc.energy.power.plant.business.opentsdb.OpentsdbOkHttpClient;
import cn.wise.sc.energy.power.plant.business.service.ICharacterParamService;
import cn.wise.sc.energy.power.plant.business.service.IEventInfoService;
import cn.wise.sc.energy.power.plant.business.service.impl.EventInfoServiceImpl;
import cn.wise.sc.energy.power.plant.business.task.schedule.ScheduleTask;
import com.alibaba.fastjson.JSON;
import net.opentsdb.client.api.query.response.QueryResponse;
......@@ -17,8 +19,11 @@ import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
......@@ -79,6 +84,7 @@ public class IndexRealTimeTask extends ScheduleTask {
//获取kkscode
List<CharacterParamInfoVo> characterParamInfoVos ;
//全场
Map<String, List<CharacterParamInfo>> groupByDeviceId = new HashMap<>();
if ("total".equals(deviceId)) {
characterParamInfoVos = characterParamInfoList;
}else{
......@@ -112,6 +118,8 @@ public class IndexRealTimeTask extends ScheduleTask {
"定子负序电流",
})) {
//右上图
//添加量程
powerPoints.setMeasuer(characterParamInfoVos.stream().filter(item->item.getKksCode().equals(queryResult.getMetric())).findFirst().get().getMeasuringrangerulemaxvalue());
DataPower dataPower = map.getOrDefault("rightTop", new DataPower());
dataPower.setXAxis(xAxis);
dataPower.getDataList().add(powerPoints);
......@@ -194,6 +202,49 @@ public class IndexRealTimeTask extends ScheduleTask {
}
}
if("total".equals(deviceId)){
//添加报警点
DataPower dataPower4 = new DataPower();
List<EventInfoServiceImpl.AlertCount> alertCounts = iEventInfoService.countAlert();
DataPower.PowerPoints powerPoints = new DataPower.PowerPoints();
powerPoints.setName("预报警");
DataPower.PowerPoints powerPoints1 = new DataPower.PowerPoints();
powerPoints1.setName("高报警");
DataPower.PowerPoints powerPoints2 = new DataPower.PowerPoints();
powerPoints2.setName("高高报警");
DataPower.PowerPoints powerPoints3= new DataPower.PowerPoints();
powerPoints3.setName("趋势报警");
dataPower4.getDataList().add(powerPoints);
dataPower4.getDataList().add(powerPoints1);
dataPower4.getDataList().add(powerPoints2);
dataPower4.getDataList().add(powerPoints3);
//获取设备长度
Set<String> deviceNames = new TreeSet<>();
alertCounts.forEach(arg -> deviceNames.add(arg.getDeviceName()));
int idx = 0;
for (String deviceName : deviceNames) {
dataPower4.getXAxis().add(deviceName);
int finalIdx = idx;
alertCounts.forEach(arg -> {
//处理名字报警
if ("preAlert".equals(arg.getAlertLevel())) {
//预报警
dataPower4.getDataList().get(0).getValue().add( arg.getCount() + "");
} else if ("tallAlert".equals(arg.getAlertLevel())) {
//高报
dataPower4.getDataList().get(1).getValue().add( arg.getCount() + "");
} else if ("tooTallAlert".equals(arg.getAlertLevel())){
//高高报
dataPower4.getDataList().get(2).getValue().add( arg.getCount() + "");
}else{
dataPower4.getDataList().get(3).getValue().add( arg.getCount() + "");
}
});
idx++;
}
map.put("alert", dataPower4);
}
try {
List<Map.Entry<String, String>> deviceGroupMap = groupMap.get(deviceId);
//根据deviceid统一发送
......
......@@ -23,10 +23,10 @@ public class TaskCacheDataService {
@Cacheable(value = "hydroge-character", key = "#deviceId")
public List<CharacterParamInfoVo> cacheHydrogeCha(String deviceId) {
List<String> characterNames = new ArrayList<>();
characterNames.add("发电机机内氢压");
characterNames.add("机内氢压");
characterNames.add("机内氢气湿度");
characterNames.add("漏氢含量");
characterNames.add("汽端发电机冷氢温度");
characterNames.add("在线漏氢");
characterNames.add("汽端冷氢温度");
List<CharacterParamInfoVo> characterParamInfoVos =
iCharacterParamService.getCharacterByName(characterNames, "", deviceId);
return characterParamInfoVos;
......
......@@ -44,7 +44,7 @@ public class TendencyTask extends ScheduleTask {
public void run() {
ConcurrentHashMap<String, TendencyWebSocket> webSocketMap =
TendencyWebSocket.webSocketMap;
ConcurrentHashMap<String, String> deviceMap = HydrogenSystemWebSocket.deviceMap;
ConcurrentHashMap<String, String> deviceMap = TendencyWebSocket.deviceMap;
if (webSocketMap.size() == 0 || deviceMap.size() == 0) {
return;
}
......@@ -52,13 +52,13 @@ public class TendencyTask extends ScheduleTask {
Map<String, List<Map.Entry<String, String>>> groupMap = deviceMap.entrySet().stream().collect(Collectors.groupingBy(c -> c.getValue()));
//向每个webSocket推送系统实时数据
for (String deviceId : groupMap.keySet()) {
List<CharacterParamInfoVo> characterParamInfoVos = taskCacheDataService.cacheHydrogeCha(deviceId);
Map<String, String> KKsCodes = characterParamInfoVos.stream().filter(item -> IS_CONTAINS(item.getCpName(), new String[]{"汽端发电机冷氢温度"})).collect(Collectors.toMap(CharacterParamInfoVo::getKksCode, CharacterParamInfoVo::getCpName));
Long lastTime = OpentsdbOkHttpClient.queryLast(characterParamInfoVos);
for (String kkscode : groupMap.keySet()) {
List<String> kksCodeList = new ArrayList<>();
kksCodeList.add(kkscode);
Long lastTime = OpentsdbOkHttpClient.queryLastBykks(kksCodeList);
QueryResponse response = iCharacterParamService
.getRealTimeDataByKksCode(new ArrayList<>(KKsCodes.keySet()), (lastTime - 1) + "", lastTime + "", "");
.getRealTimeDataByKksCode(kksCodeList, (lastTime - 1) + "", lastTime + "", "");
//组装数据结构
List<Object> xAxis = response.getResults().get(0).getDps().keySet().stream().map(item -> item.toString()).collect(Collectors.toList());
......@@ -66,22 +66,19 @@ public class TendencyTask extends ScheduleTask {
for (QueryResult queryResult : response.getResults()) {
DataPower.PowerPoints powerPoints = new DataPower.PowerPoints();
powerPoints.setKksCode(queryResult.getMetric());
powerPoints.setName(KKsCodes.get(queryResult.getMetric()));
List<String> finalList = new ArrayList<>();
queryResult.getDps().values().stream().forEach(item -> {
finalList.add(item.toString());
});
powerPoints.setValue(finalList);
if (KKsCodes.get(queryResult.getMetric()).contains("汽端发电机冷氢温度")) {
DataPower dataPower = map.getOrDefault("rightBottom", new DataPower());
DataPower dataPower = map.getOrDefault("data", new DataPower());
dataPower.setXAxis(xAxis);
dataPower.getDataList().add(powerPoints);
map.putIfAbsent("rightBottom", dataPower);
map.putIfAbsent("data", dataPower);
}
//左上图
}
try {
List<Map.Entry<String, String>> deviceGroupMap = groupMap.get(deviceId);
List<Map.Entry<String, String>> deviceGroupMap = groupMap.get(kkscode);
//根据deviceid统一发送
for (Map.Entry<String, String> entry : deviceGroupMap) {
final SendWebSocket webSocket = webSocketMap.get(entry.getKey());
......
......@@ -25,7 +25,7 @@ import java.util.concurrent.ConcurrentHashMap;
**/
@Slf4j
@Component
@ServerEndpoint("/tendency/{deviceId}")
@ServerEndpoint("/tendency/{kkscode}")
@DependsOn("myApplicationContextAware")
public class TendencyWebSocket implements SendWebSocket{
......@@ -44,29 +44,26 @@ public class TendencyWebSocket implements SendWebSocket{
private Session session;
private String uuid;
private HydrogeSystem1Task hydrogeSystem1Task = (HydrogeSystem1Task) MyApplicationContextAware.getApplicationContext().getBean("hydrogeSystem1Task");
private HydrogeSystem3Task hydrogeSystem3Task = (HydrogeSystem3Task) MyApplicationContextAware.getApplicationContext().getBean("hydrogeSystem3Task");
private TendencyTask tendencyTask = (TendencyTask) MyApplicationContextAware.getApplicationContext().getBean("tendencyTask");
/**
* 连接建立成功调用的方法
*/
@OnOpen
public void onOpen(Session session, @PathParam("deviceId") String deviceId) {
public void onOpen(Session session, @PathParam("kkscode") String kkscode) {
this.session = session;
uuid = UUID.randomUUID().toString();
deviceMap.put(uuid, deviceId);
deviceMap.put(uuid, kkscode);
webSocketMap.put(uuid, this);
//加入set中
addOnlineCount();
//启动任务
ScheduleUtil.start(hydrogeSystem1Task,1000);
ScheduleUtil.start(hydrogeSystem3Task,1000*3600);
ScheduleUtil.start(tendencyTask,1000);
//已有用户的情况,主动推送一次
if (webSocketMap.size() > 1) {
hydrogeSystem1Task.run();
hydrogeSystem3Task.run();
tendencyTask.run();
}
log.info("用户连接:" + deviceId + ",当前在线人数为:" + getOnlineCount());
log.info("用户连接:" + kkscode + ",当前在线人数为:" + getOnlineCount());
}
/**
......@@ -81,8 +78,7 @@ public class TendencyWebSocket implements SendWebSocket{
subOnlineCount();
}
if (webSocketMap.size() == 0) {
ScheduleUtil.cancel(hydrogeSystem1Task);
ScheduleUtil.cancel(hydrogeSystem3Task);
ScheduleUtil.cancel(tendencyTask);
}
log.info("用户退出:" + uuid + ",当前在线人数为:" + getOnlineCount());
}
......
package cn.wise.sc.energy.power.plant.business.utils.poi;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.resource.ClassPathResource;
import cn.wise.sc.energy.power.plant.business.domain.AutoInspection;
import cn.wise.sc.energy.power.plant.business.repository.AutoInspectionRepository;
import cn.wise.sc.energy.power.plant.common.core.exception.ResponseEnum;
import com.alibaba.fastjson.JSONObject;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFHeader;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
/**
* @author shulidong
* @since 2020/9/21 14:04
*/
@Service
public class DocxService {
@Autowired
AutoInspectionRepository autoInspectionRepository;
private static final Logger LOGGER = LoggerFactory.getLogger(DocxService.class);
public byte[] fillDocx() throws Exception {
List<AutoInspection> list = autoInspectionRepository.findAutoInspectionsById("C0A001 - 1 - 1600756452620");
if (CollectionUtil.isEmpty(list)) {
ResponseEnum.BUSINESS_ERROR.newException("未找到相应的报告项");
}
final InputStream inputStream = new ClassPathResource("templates/" + "demo1.docx").getStream();
XWPFDocument document = new XWPFDocument(inputStream);
//添加页眉 需要固定的文字(中文标点)在模板上->{{:text:date:date:}}
List<XWPFHeader> pageHeaders = document.getHeaderList();
JSONObject original = new JSONObject();
JSONObject date = new JSONObject();
date.put("date",LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
original.put("date", date);
for (int i = 0; i < pageHeaders.size(); i++) {
XWPFHeader pageHeader = pageHeaders.get(i);
List<XWPFParagraph> headerPara = pageHeader.getParagraphs();
XWPFParagraph headerParagraph = headerPara.get(0);
if (headerParagraph.getRuns().size() > 1) {
PoiiUtiil.parseThisParagraph(headerParagraph,original);
}
}
//获取所有的段落
List<XWPFParagraph> paragraphs = document.getParagraphs();
//把文档groupby
List<XWPFParagraph> texts = new ArrayList<>();
List<XWPFTable> tables = new ArrayList<>();
for (XWPFParagraph paragraph : paragraphs) {
String text = paragraph.getText();
//只有这三种标签能够混用
if (text.contains("{{:text") || text.contains("{{:for") || text.contains("{{:desc")) {
texts.add(paragraph);
}
}
for (XWPFTable table : document.getTables()) {
if (table == null) {
LOGGER.error("table is null, please stop!");
}
if (table.getText().contains("{{:table") || table.getText().contains("{{:text")) {
tables.add(table);
}
}
JSONObject allin = new JSONObject();
JSONObject fuzhu = new JSONObject();
fuzhu.put("MKW05CP001", 12.578);
allin.put("fuzhu", fuzhu);
JSONObject reportInfo = new JSONObject();
reportInfo.put("username", "张三");
reportInfo.put("a", "张三");
reportInfo.put("date", LocalDateTime.now().format(DateTimeFormatter.BASIC_ISO_DATE).toString());
allin.put("reportInfo", reportInfo);
try {
PoiiUtiil.paragraph(texts, allin);
PoiiUtiil.table(tables, allin);
//要求word在打开时提示更新域
document.enforceUpdateFields();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
FileOutputStream fos = new FileOutputStream("D:/"+ "生成文件.docx");
document.write(fos);
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
package cn.wise.sc.energy.power.plant.business.poi;
package cn.wise.sc.energy.power.plant.business.utils.poi;
import cn.afterturn.easypoi.entity.ImageEntity;
import lombok.extern.slf4j.Slf4j;
......
package cn.wise.sc.energy.power.plant.business.utils.poi;
/**
* @author qilei
* @since 2018-05-15 16:50
*/
public interface POIConstance {
/**
* A4纸的宽度。
*/
Integer A4_TABLE_EARLY_AND_REVIEW_WIDTH = 8494;
Integer A4_TABLE_TENDER_WIDTH = 8290;
/**
* 4个空格
*/
Integer FOUR_SPACE = 420;
}
package cn.wise.sc.energy.power.plant.business.utils.poi;
import cn.afterturn.easypoi.entity.ImageEntity;
import cn.afterturn.easypoi.util.PoiPublicUtil;
import cn.afterturn.easypoi.word.parse.excel.ExcelMapParse;
import cn.wise.sc.energy.power.plant.business.constant.Constance;
import cn.wise.sc.energy.power.plant.common.core.exception.ResponseEnum;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblGrid;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblGridCol;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static cn.afterturn.easypoi.util.PoiElUtil.EMPTY;
import static cn.afterturn.easypoi.util.PoiElUtil.END_STR;
import static cn.afterturn.easypoi.util.PoiElUtil.FOREACH;
import static cn.afterturn.easypoi.util.PoiElUtil.START_STR;
/**
* @author shulidong
* @since 2020/9/20 17:03
*/
public class PoiiUtiil {
private static final Logger LOGGER = LoggerFactory.getLogger(PoiiUtiil.class);
private static String defaultTextSource = "reportInfo";
//读取配置文件
//text,for,chart三种标签都不获取配置,直接在语句里读取
public static void paragraph(List<XWPFParagraph> paragraphs, JSONObject ordinal) throws Exception {
for (XWPFParagraph paragraph : paragraphs) {
parseThisParagraph(paragraph, ordinal);
}
}
public static void parseThisParagraph(XWPFParagraph paragraph, JSONObject textSource) throws Exception {
XWPFRun run;
// 拿到的第一个run,用来set值,可以保存格式
XWPFRun currentRun = null;
// 存放当前的text
String currentText = "";
String text;
// 判断是不是已经遇到{{
Boolean isfinde = false;
// 存储遇到的run,把他们置空
List<Integer> runIndex = new ArrayList<Integer>();
for (int i = 0; i < paragraph.getRuns().size(); i++) {
run = paragraph.getRuns().get(i);
text = run.getText(0);
if (org.apache.commons.lang3.StringUtils.isEmpty(text)) {
continue;
} // 如果为空或者""这种这继续循环跳过
if (isfinde) {
currentText += text;
if (currentText.indexOf(START_STR) == -1) {
isfinde = false;
runIndex.clear();
} else {
runIndex.add(i);
}
if (currentText.indexOf(END_STR) != -1) {
changeValues(paragraph, currentRun, currentText, runIndex, textSource);
currentText = "";
isfinde = false;
}
// 判断是不是开始,考虑单个‘{’的情况
} else if (text.indexOf(START_STR) >= 0 || text.indexOf("{") >= 0) {
currentText = text;
isfinde = true;
currentRun = run;
} else {
currentText = "";
}
if (currentText.indexOf(END_STR) != -1) {
changeValues(paragraph, currentRun, currentText, runIndex, textSource);
isfinde = false;
}
}
}
/**
* 根据条件改变值
*/
private static void changeValues(XWPFParagraph paragraph, XWPFRun currentRun, String currentText,
List<Integer> runIndex, JSONObject map) throws Exception {
// 判断是不是迭代输出
if (currentText.contains(FOREACH) && currentText.startsWith(START_STR)) {
currentText = currentText.replace(FOREACH, EMPTY).replace(START_STR, EMPTY).replace(END_STR, EMPTY);
String[] keys = currentText.replaceAll("\\s{1,}", " ").trim().split(" ");
List list = (List) PoiPublicUtil.getParamsValue(keys[0], map);
list.forEach(obj -> {
if (obj instanceof ImageEntity) {
currentRun.setText("", 0);
ExcelMapParse.addAnImage((ImageEntity) obj, currentRun);
} else {
PoiPublicUtil.setWordText(currentRun, obj.toString());
}
});
} else {
Object obj = getRealValue(currentText, map);
// 如果是图片就设置为图片
if (obj instanceof ImageEntity) {
currentRun.setText("", 0);
ExcelMapParse.addAnImage((ImageEntity) obj, currentRun);
} else {
currentText = obj.toString();
PoiPublicUtil.setWordText(currentRun, currentText);
}
}
for (int k = 0; k < runIndex.size(); k++) {
paragraph.getRuns().get(runIndex.get(k)).setText("", 0);
}
runIndex.clear();
}
public static Object getRealValue(String currentText, JSONObject map) throws Exception {
String params = "";
String[] param = currentText.split(Constance.SPLIT);
if (param.length < 4) {
ResponseEnum.BUSINESS_ERROR.newException("expression lost something->缺少':'");
}
JSONObject textSource;
if (StringUtils.isEmpty(map.get(param[2]))) {
textSource = (JSONObject) map.get(defaultTextSource);
} else {
textSource = (JSONObject) map.get(param[2]);
}
if (textSource == null) {
ResponseEnum.BUSINESS_ERROR.newException("未找到匹配的解析类");
}
String text = StringUtils.isEmpty(textSource.getString(param[3])) ? "" : textSource.getString(param[3]);
params = currentText.substring(currentText.indexOf("{{") + 2, currentText.indexOf("}}"));
currentText = currentText.replace("{{" + params + "}}", text);
return currentText;
}
/**
* {{:table:source:id:col:}}
*
* @param tables
* @param ordinal
* @param tableAttr
*/
public static void table(List<XWPFTable> tables, JSONObject ordinal, Map<String, String> tableAttr) {
for (XWPFTable table : tables) {
//获取table的头信息 {{:table:source:name:type:}}
if (table.getText().contains("{{:text")) {
List<XWPFTableCell> cells = new ArrayList<>();
for (int i = 0; i < table.getRows().size(); i++) {
XWPFTableRow row = table.getRow(i);
for (XWPFTableCell cell : row.getTableCells()) {
if (cell.getText().contains(":text:")) {
cells.add(cell);
}
}
}
for (int ii = 0; ii < cells.size(); ii++) {
XWPFTableCell cell = cells.get(ii);
String[] innCellParams = cell.getText().split(":");
JSONObject textSource;
if (StringUtils.isEmpty(ordinal.get(innCellParams[2]))) {
textSource = (JSONObject) ordinal.get(defaultTextSource);
} else {
textSource = (JSONObject) ordinal.get(innCellParams[2]);
}
//清除掉已有的paragraph
cell.removeParagraph(0);
cell.addParagraph();
XWPFTableRow row = table.getRow(ii);
}
}
if (table.getText().contains("{{:table")) {
String[] tab = table.getText().split(Constance.SPLIT);
int originalRowNum = table.getRows().size();
JSONArray tableList = ordinal.getJSONArray(tab[2]);
if (tableList == null || tableList.isEmpty()) {
continue;
}
//表头字段
if (tableAttr.get(tab[3]) == null) {
LOGGER.error(tab[3] + "");
}
String[] params = tableAttr.get(tab[3]).split(splitBySymbol(tableAttr.get(tab[3])));
//表格类型是竖向写还是横向写,不写的话默认横向
String type = "row";
LOGGER.info(tab[3] + "开始填充");
if (!StringUtils.isEmpty(tab[4])) {
type = tab[4];
}
for (int k = 0; k < tableList.size(); k++) {
JSONObject sourceObj = tableList.getJSONObject(k);
sourceObj.put("blankStr", "");
//竖向写表格
if ("col".equals(type)) {
for (int i = 0; i < table.getRows().size(); i++) {
XWPFTableRow row = table.getRow(i);
if (i > 0) {
row.setHeight(300);
}
XWPFTableCell cell = row.createCell();
}
}
//横向写表格
if ("row".equals(type)) {
table.createRow();
XWPFTableRow row = table.getRow(originalRowNum + k);
row.setHeight(300);
for (int i = 0; i < row.getTableCells().size(); i++) {
XWPFTableCell cell = row.getCell(i);
}
}
}
//竖向表格动态设置列宽
if ("col".equals(type)) {
int colLength = tableList.size() + Integer.parseInt(tab[5]);
TableUtil.setTableWidth(table, POIConstance.A4_TABLE_TENDER_WIDTH);
setTableGridCol(table, colLength, POIConstance.A4_TABLE_TENDER_WIDTH);
}
//清除掉表格头标记
XWPFTableCell cell0 = table.getRow(0).getCell(0);
cell0.getParagraphs().get(0).getRuns().get(0).setText("", 0);
}
}
}
/**
* {{:table:source:id:col:}}
*
* @param tables
* @param ordinal
*/
public static void table(List<XWPFTable> tables, JSONObject ordinal) throws Exception {
for (XWPFTable table : tables) {
//获取table的头信息 {{:table:source:name:type:}}
if (table.getText().contains("{{:text")) {
List<XWPFTableCell> cells = new ArrayList<>();
for (int i = 0; i < table.getRows().size(); i++) {
XWPFTableRow row = table.getRow(i);
for (XWPFTableCell cell : row.getTableCells()) {
if (cell.getText().contains(":text:")) {
cells.add(cell);
}
}
}
for (int ii = 0; ii < cells.size(); ii++) {
XWPFTableCell cell = cells.get(ii);
XWPFTableRow row = table.getRow(ii);
setCellRun(ordinal, cell);
}
}
}
}
/**
* 设置cell的run的文本样式
*
* @param sourceObj
* @param cell
*/
private static void setCellRun(JSONObject sourceObj, XWPFTableCell cell) throws Exception {
XWPFParagraph paragraph = cell.getParagraphs().get(0);
paragraph.setAlignment(ParagraphAlignment.CENTER);
parseThisParagraph(paragraph,sourceObj);
cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
}
/**
* @Description: 设置表格列宽
*/
private static void setTableGridCol(XWPFTable table, int colLength, int tableWidth) {
CTTbl ttbl = table.getCTTbl();
CTTblGrid tblGrid = ttbl.getTblGrid() != null ? ttbl.getTblGrid() : ttbl.addNewTblGrid();
for (int j = 0; j < colLength; j++) {
CTTblGridCol gridCol = tblGrid.addNewGridCol();
gridCol.setW(new BigInteger(String.valueOf(tableWidth / colLength)));
}
}
//分隔符语法扩展 支持 |,&,*,%,@,!,$,~,- 不能用:
private static String splitBySymbol(String str) {
List<String> partations = new ArrayList<>();
Pattern p = Pattern.compile("(\\|)|\\&|\\*|\\%|\\@|\\!|\\$|\\~|\\-");
Matcher m = p.matcher(str);
boolean unContainsSymbol = true;
String symbol = ":";
if (m.find()) {
symbol = m.group();
}
return "\\" + symbol;
}
}
package cn.wise.sc.energy.power.plant.business.utils.poi;
import cn.wise.sc.energy.power.plant.business.utils.poi.styles.POIColor;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblGrid;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblGridCol;
import java.math.BigInteger;
public class StyleUtil {
/**
* @Description: 设置表格列宽
*/
private static void setTableGridCol(XWPFTable table, int colLength, int tableWidth) {
CTTbl ttbl = table.getCTTbl();
CTTblGrid tblGrid = ttbl.getTblGrid() != null ? ttbl.getTblGrid() : ttbl.addNewTblGrid();
for (int j = 0; j < colLength; j++) {
CTTblGridCol gridCol = tblGrid.addNewGridCol();
gridCol.setW(new BigInteger(String.valueOf(tableWidth / colLength)));
}
}
/**
* 简单的设置字体和字号,为run设置
*
* @param run
* @param fontSizeMutiply2 字号*2 比如要设置10.5号字,就传入21
* @param englishFont Nullable
* @param chineseFont Nullable
*/
public static void setFontAndSize(XWPFRun run, int fontSizeMutiply2, String englishFont, String chineseFont) {
run.setColor(POIColor.BLACK.toString());
//给字体赋值,避免设置字体时出现null
run.setFontFamily(chineseFont == null ? "宋体" : chineseFont);
//给字号赋值,避免设置字号时出现null
run.setFontSize(9);
//这地方 因为fontSize不存在小数点,所以很蛋疼,这里的BigInteger是fontSize*2,看源码即可知道。
run.getCTR().getRPr().getSz().setVal(new BigInteger(fontSizeMutiply2 + ""));
//设置英文字体
run.getCTR().getRPr().getRFonts().setAscii(englishFont == null ? "Times New Roman" : englishFont);
//设置中文字体
run.getCTR().getRPr().getRFonts().setEastAsia(chineseFont == null ? "宋体" : chineseFont);
}
}
package cn.wise.sc.energy.power.plant.business.utils.poi;
import cn.wise.sc.energy.power.plant.business.constant.Constance;
import cn.wise.sc.energy.power.plant.business.utils.poi.styles.Style;
import cn.wise.sc.energy.power.plant.business.utils.poi.xwpftable.ToolXWPFCell;
import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
import org.apache.poi.xwpf.usermodel.TextAlignment;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblWidth;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STMerge;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STTblWidth;
import java.math.BigInteger;
/**
* @author qilei
* @since 2018-04-09 11:51
*/
public class TableUtil {
/**
* table必须是新的,也就是只有一行一列,否则会出现格式错乱。
*
* @param table
* @param headers
*/
@Deprecated
public static void buildHeader(XWPFTable table, String... headers) {
final XWPFParagraph xwpfParagraph1 = table.getRow(0).getCell(0).getParagraphs().get(0);
xwpfParagraph1.setAlignment(ParagraphAlignment.CENTER);
xwpfParagraph1.setSpacingBetween(1);
final XWPFRun run1 = xwpfParagraph1.createRun();
run1.setText(headers[0]);
WordUtil.setFontAndSize(run1, 18, null, null);
for (int i = 1; i < headers.length; i++) {
final XWPFParagraph xwpfParagraph = table.getRow(0).createCell().getParagraphs().get(0);
xwpfParagraph.setAlignment(ParagraphAlignment.CENTER);
xwpfParagraph.setSpacingBetween(1);
xwpfParagraph.setVerticalAlignment(TextAlignment.CENTER);
final XWPFRun run = xwpfParagraph.createRun();
run.setText(headers[i]);
WordUtil.setFontAndSize(run, 18, null, null);
}
}
@Deprecated
public static void appendContent(XWPFTable table, String... contentLine) {
XWPFTableRow row = table.createRow();
for (int i = 0; i < contentLine.length; i++) {
final XWPFParagraph xwpfParagraph = row.getCell(i).getParagraphs().get(0);
xwpfParagraph.setAlignment(ParagraphAlignment.CENTER);
xwpfParagraph.setSpacingBetween(1);
final XWPFRun run = xwpfParagraph.createRun();
run.setText(contentLine[i]);
WordUtil.setFontAndSize(run, 18, null, null);
}
}
@Deprecated
public static void buildeColumnHeader(XWPFTable table, String... headers) {
final XWPFParagraph xwpfParagraph1 = table.getRow(0).getCell(0).getParagraphs().get(0);
xwpfParagraph1.setAlignment(ParagraphAlignment.CENTER);
xwpfParagraph1.setSpacingBetween(1);
final XWPFRun run1 = xwpfParagraph1.createRun();
run1.setText(headers[0]);
WordUtil.setFontAndSize(run1, 18, null, null);
for (int i = 1; i < headers.length; i++) {
final XWPFParagraph xwpfParagraph = table.createRow().getCell(0).getParagraphs().get(0);
xwpfParagraph.setAlignment(ParagraphAlignment.CENTER);
xwpfParagraph.setSpacingBetween(1);
final XWPFRun run = xwpfParagraph.createRun();
run.setText(headers[i]);
WordUtil.setFontAndSize(run, 18, null, null);
}
}
@Deprecated
public static void appendColumnContent(XWPFTable table, String... contentLine) {
for (int i = 0; i < contentLine.length; i++) {
final XWPFParagraph xwpfParagraph = table.getRow(i).createCell().getParagraphs().get(0);
xwpfParagraph.setAlignment(ParagraphAlignment.CENTER);
xwpfParagraph.setSpacingBetween(1);
final XWPFRun run = xwpfParagraph.createRun();
run.setText(contentLine[i]);
WordUtil.setFontAndSize(run, 18, null, null);
}
}
/**
* 对于表格组件的使用,主要需求有按照行列去构建一个table,除此之外,对于每个单元格的样式也是有要求的。在控制样式的同时,要对行高和列宽同时控制,此时需要能够联动的去扩展。
*/
/**
* table必须是新的,也就是只有一行一列,否则会出现格式错乱。
*
* @param table
* @param cells
*/
public static void buildRowHeader(XWPFTable table, ToolXWPFCell... cells) {
if (cells.length == 0) {//todo
return;
}
final XWPFTableCell cell0 = table.getRow(0).getCell(0);
final XWPFParagraph xwpfParagraph1 = cell0.getParagraphs().get(0);
Style.DEFAULT_TABLE_CONTENT_STYLE.proccess(xwpfParagraph1);
//第一个单元格。
for (int i = 0; i < cells[0].getRuns().size(); i++) {
//处理首行换行符
final String[] contents = cells[0].getRuns().get(i).getContent().split(Constance.RETURN);
for (int k = 0; k < contents.length; k++) {
final XWPFRun run = xwpfParagraph1.createRun();
run.setText(contents[k]);
if (k + 1 < contents.length) {
run.addBreak();
}
cells[0].getRuns().get(i).getStyle().proccess(run);
}
}
//trick 居中问题
cell0.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
//下面的单元格
for (int i = 1; i < cells.length; i++) {
final XWPFTableCell cell = table.getRow(0).createCell();
final XWPFParagraph xwpfParagraphPer = cell.getParagraphs().get(0);
Style.DEFAULT_TABLE_CONTENT_STYLE.proccess(xwpfParagraphPer);
for (int j = 0; j < cells[i].getRuns().size(); j++) {
//处理换行符的
final String[] contents = cells[i].getRuns().get(j).getContent().split(Constance.RETURN);
for (int k = 0; k < contents.length; k++) {
final XWPFRun run = xwpfParagraphPer.createRun();
run.setText(contents[k]);
if (k + 1 < contents.length) {
run.addBreak();
}
cells[i].getRuns().get(j).getStyle().proccess(run);
}
//如果该行为空,就设置为continue
if (cells[i] == ToolXWPFCell.CONTINUE) {
cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE);
continue;
}
//如果没有下一行,就直接continue
if (i + 1 >= cells.length) {
continue;
} else if (cells[i + 1] == ToolXWPFCell.CONTINUE) {
//如果下一个为空,就设置成RESTART
cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);
}
}
//trick 因为默认都是靠上居中,尤其横着生成的首行,就是靠上居中的 不合要求
cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
}
}
public static void buildElecRowHeader(XWPFTable table, ToolXWPFCell... cells) {
if (cells.length == 0) {//todo
return;
}
final XWPFTableCell cell0 = table.getRow(0).getCell(0);
final XWPFParagraph xwpfParagraph1 = cell0.getParagraphs().get(0);
Style.ELEC_TABLE_CONTENT_STYLE.proccess(xwpfParagraph1);
//第一个单元格。
for (int i = 0; i < cells[0].getRuns().size(); i++) {
//处理首行换行符
final String[] contents = cells[0].getRuns().get(i).getContent().split(Constance.RETURN);
for (int k = 0; k < contents.length; k++) {
final XWPFRun run = xwpfParagraph1.createRun();
run.setText(contents[k]);
if (k + 1 < contents.length) {
run.addBreak();
}
cells[0].getRuns().get(i).getStyle().proccess(run);
}
}
//trick 居中问题
cell0.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
//下面的单元格
for (int i = 1; i < cells.length; i++) {
final XWPFTableCell cell = table.getRow(0).createCell();
final XWPFParagraph xwpfParagraphPer = cell.getParagraphs().get(0);
Style.ELEC_TABLE_CONTENT_STYLE.proccess(xwpfParagraphPer);
for (int j = 0; j < cells[i].getRuns().size(); j++) {
//处理换行符的
final String[] contents = cells[i].getRuns().get(j).getContent().split(Constance.RETURN);
for (int k = 0; k < contents.length; k++) {
final XWPFRun run = xwpfParagraphPer.createRun();
run.setText(contents[k]);
if (k + 1 < contents.length) {
run.addBreak();
}
cells[i].getRuns().get(j).getStyle().proccess(run);
}
//如果该行为空,就设置为continue
if (cells[i] == ToolXWPFCell.CONTINUE) {
cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE);
continue;
}
//如果没有下一行,就直接continue
if (i + 1 >= cells.length) {
continue;
} else if (cells[i + 1] == ToolXWPFCell.CONTINUE) {
//如果下一个为空,就设置成RESTART
cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);
}
}
//trick 因为默认都是靠上居中,尤其横着生成的首行,就是靠上居中的 不合要求
cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
}
}
public static void appendRowContent(XWPFTable table, ToolXWPFCell... cells) {
XWPFTableRow row = table.createRow();
row.setHeight(300);
for (int i = 0; i < cells.length; i++) {
final XWPFTableCell cell = row.getCell(i);
cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
final XWPFParagraph xwpfParagraphPer = cell.getParagraphs().get(0);
Style.DEFAULT_TABLE_CONTENT_STYLE.proccess(xwpfParagraphPer);
for (int j = 0; j < cells[i].getRuns().size(); j++) {
//处理换行符的
final String[] contents = cells[i].getRuns().get(j).getContent().split(Constance.RETURN);
for (int k = 0; k < contents.length; k++) {
final XWPFRun run = xwpfParagraphPer.createRun();
String content = contents[k];
run.setText(content);
if (k + 1 < contents.length) {
run.addBreak();
}
cells[i].getRuns().get(j).getStyle().proccess(run);
}
//如果该行为空,就设置为continue
if (cells[i] == ToolXWPFCell.CONTINUE) {
cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE);
continue;
}
//如果没有下一行,就直接continue
if (i + 1 >= cells.length) {
continue;
} else if (cells[i + 1] == ToolXWPFCell.CONTINUE) {
//如果下一个为空,就设置成RESTART
cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);
}
}
}
}
public static void appendElecRowContent(XWPFTable table, ToolXWPFCell... cells) {
XWPFTableRow row = table.createRow();
for (int i = 0; i < cells.length; i++) {
final XWPFTableCell cell = row.getCell(i);
cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
final XWPFParagraph xwpfParagraphPer = cell.getParagraphs().get(0);
Style.ELEC_TABLE_CONTENT_STYLE.proccess(xwpfParagraphPer);
for (int j = 0; j < cells[i].getRuns().size(); j++) {
//处理换行符的
final String[] contents = cells[i].getRuns().get(j).getContent().split(Constance.RETURN);
for (int k = 0; k < contents.length; k++) {
final XWPFRun run = xwpfParagraphPer.createRun();
run.setText(contents[k]);
if (k + 1 < contents.length) {
run.addBreak();
}
cells[i].getRuns().get(j).getStyle().proccess(run);
}
//如果该行为空,就设置为continue
if (cells[i] == ToolXWPFCell.CONTINUE) {
cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE);
continue;
}
//如果没有下一行,就直接continue
if (i + 1 >= cells.length) {
continue;
} else if (cells[i + 1] == ToolXWPFCell.CONTINUE) {
//如果下一个为空,就设置成RESTART
cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);
}
}
}
}
/**
* 清除一个word tablecell中的内容。
* 保留第一个Paragraph,清除其中的run。
*
* @param cell
*/
public static void clearMe(XWPFTableCell cell) {
for (int i = cell.getParagraphs().size(); i > 1; i--) {
cell.removeParagraph(0);
}
WordUtil.clearMe(cell.getParagraphs().get(0));
}
/**
* 对XWPFTable设置宽度,默认设置A4的宽度。
*
* @param table
*/
public static void setTableWidth(XWPFTable table) {
setTableWidth(table, POIConstance.A4_TABLE_EARLY_AND_REVIEW_WIDTH);
}
/**
* 对XWPFTable设置宽度
*
* @param table
* @param width
*/
public static void setTableWidth(XWPFTable table, int width) {
CTTblWidth ctTblWidth = table.getCTTbl().addNewTblPr().addNewTblW();
ctTblWidth.setType(STTblWidth.DXA);
ctTblWidth.setW(BigInteger.valueOf(width));
}
/**
* 重写单元格内容,采用单元格已有的第一个样式
*
* @param cell
* @param value
*/
public static void rewriteCell(XWPFTableCell cell, String value) {
for (XWPFParagraph xwpfParagraph : cell.getParagraphs()) {
WordUtil.clearMe(xwpfParagraph);
}
final XWPFRun run = cell.getParagraphs().get(0).createRun();
run.setText(value);
}
/**
* 重写单元格内容,使用指定的样式
*
* @param cell
* @param value
*/
public static void rewriteCell(XWPFTableCell cell, String value, Style style) {
clearMe(cell);
final XWPFRun run = cell.addParagraph().createRun();
run.setText(value);
style.proccess(run);
}
}
package cn.wise.sc.energy.power.plant.business.utils.poi;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import cn.afterturn.easypoi.entity.ImageEntity;
import org.jfree.chart.ChartUtils;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.SpiderWebPlot;
import org.jfree.chart.title.LegendTitle;
import org.jfree.chart.title.TextTitle;
import org.jfree.chart.ui.RectangleEdge;
import org.jfree.data.category.DefaultCategoryDataset;
/**
* @author 何昌杰
*/
public class WordDemo1 {
public static void main(String[] args) throws IOException {
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
String group1 = "huawei ";
dataset.addValue(5, group1, "w1");
dataset.addValue(6, group1, "w2");
dataset.addValue(4, group1, "w3");
dataset.addValue(2, group1, "w4");
dataset.addValue(5, group1, "w5");
dataset.addValue(5, group1, "w6");
dataset.addValue(5, group1, "w7");
dataset.addValue(8, group1, "w8");
group1 = "apple ";
dataset.addValue(2, group1, "w1");
dataset.addValue(4, group1, "w2");
dataset.addValue(4, group1, "w3");
dataset.addValue(5, group1, "w4");
dataset.addValue(5, group1, "w5");
dataset.addValue(8, group1, "w6");
dataset.addValue(9, group1, "w7");
dataset.addValue(8, group1, "w8");
SpiderWebPlot spiderwebplot = new SpiderWebPlot(dataset);
JFreeChart jfreechart = new JFreeChart("Test", TextTitle.DEFAULT_FONT, spiderwebplot, false);
LegendTitle legendtitle = new LegendTitle(spiderwebplot);
legendtitle.setPosition(RectangleEdge.TOP);
jfreechart.addSubtitle(legendtitle);
ByteArrayOutputStream out = new ByteArrayOutputStream();
ChartUtils.writeChartAsPNG(out, jfreechart, 400, 500);
ImageEntity imageEntity = new ImageEntity(out.toByteArray(), 200, 200);
//word模板相对路径、word生成路径、word生成的文件名称、数据源
HashMap<String, Object> map = new HashMap<>(4);
long startTime = System.currentTimeMillis();
//模拟饼状图数据
HashMap<String, Integer> datas = new HashMap<>(3);
datas.put("一号", 10);
datas.put("二号", 20);
datas.put("三号", 40);
ImageEntity imageEntity1 = JfreeUtil.pieChart("测试", datas, 200, 200);
map.put("picture", imageEntity);
map.put("picture1", imageEntity1);
//模拟其它普通数据
map.put("username", "张三");
map.put("date", "2019-10-10");
map.put("desc", "测试");
map.put("boo", true);
//模拟表格数据
ArrayList<HashMap<String, String>> list = new ArrayList<>(2);
HashMap<String, String> temp = new HashMap<>(3);
temp.put("sn", "1");
temp.put("name", "第一个人");
temp.put("age", "23");
list.add(temp);
for (int i = 0; i < 100; i++) {
temp = new HashMap<>(3);
temp.put("sn", "2");
temp.put("name", "第二个人");
temp.put("age", "24");
list.add(temp);
}
map.put("personlist", list);
// WordUtils.exportWord("C:\\Users\\admin\\Desktop\\template\\demo1.docx", "D:/", "生成文件.docx", map);
}
}
\ No newline at end of file
package cn.wise.sc.energy.power.plant.business.utils.poi;
import cn.wise.sc.energy.power.plant.business.utils.poi.styles.POIColor;
import cn.wise.sc.energy.power.plant.business.utils.poi.styles.Style;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFFieldRun;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.xmlbeans.XmlCursor;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSimpleField;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STOnOff;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
/**
* @author qilei
* @since 2018-03-20 09:56
*/
public class WordUtil {
public static void insert2PicturesAndDescribeAfter(XWPFDocument docx, XWPFParagraph currentParagraph, InputStream pic1, InputStream pic2, String picDescribe) throws IOException, InvalidFormatException {
XmlCursor xmlCursor = currentParagraph.getCTP().newCursor();
xmlCursor.toNextSibling();
final XWPFParagraph paragraph = docx.insertNewParagraph(xmlCursor);
paragraph.setAlignment(ParagraphAlignment.CENTER);
final XWPFRun run1 = paragraph.createRun();
run1.addPicture(pic1, XWPFDocument.PICTURE_TYPE_PNG, "", Units.toEMU(205.208), Units.toEMU(153.906));
run1.addPicture(pic2, XWPFDocument.PICTURE_TYPE_PNG, "", Units.toEMU(205.208), Units.toEMU(153.906));
final XmlCursor xmlCursor1 = paragraph.getCTP().newCursor();
xmlCursor1.toNextSibling();
final XWPFParagraph paragraph1 = docx.insertNewParagraph(xmlCursor1);
paragraph1.createRun().setText(picDescribe);
Style.DEFAULT_TABLE_PIC_NAME_STYLE.proccess(paragraph1);
}
public static XWPFParagraph insertPictureAndDescribeAfter(XWPFDocument docx, XWPFParagraph currentParagraph, InputStream picStream, String picDescribe) throws IOException, InvalidFormatException {
XmlCursor xmlCursor = currentParagraph.getCTP().newCursor();
xmlCursor.toNextSibling();
final XWPFParagraph paragraph = docx.insertNewParagraph(xmlCursor);
paragraph.setAlignment(ParagraphAlignment.CENTER);
final XWPFRun run = paragraph.createRun();
run.addPicture(picStream, XWPFDocument.PICTURE_TYPE_PNG, "", Units.toEMU(320), Units.toEMU(240));
final XmlCursor xmlCursor1 = paragraph.getCTP().newCursor();
xmlCursor1.toNextSibling();
final XWPFParagraph paragraph1 = docx.insertNewParagraph(xmlCursor1);
final XWPFRun run1 = paragraph1.createRun();
run1.setText(picDescribe);
Style.DEFAULT_TABLE_PIC_NAME_STYLE.proccess(paragraph1);
return paragraph1;
}
/**
* 仅插入图片 不做描述
*
* @param docx
* @param currentParagraph
* @param picStream
* @return
* @throws IOException
* @throws InvalidFormatException
*/
public static XWPFParagraph insertPicture(XWPFDocument docx, XWPFParagraph currentParagraph, InputStream picStream) throws IOException, InvalidFormatException {
XmlCursor xmlCursor = currentParagraph.getCTP().newCursor();
xmlCursor.toNextSibling();
final XWPFParagraph paragraph = docx.insertNewParagraph(xmlCursor);
paragraph.setAlignment(ParagraphAlignment.CENTER);
final XWPFRun run = paragraph.createRun();
run.addPicture(picStream, XWPFDocument.PICTURE_TYPE_PNG, "", Units.toEMU(320), Units.toEMU(240));
return paragraph;
}
public static XWPFParagraph insert2Pictures(XWPFDocument docx, XWPFParagraph currentParagraph, InputStream pic1, InputStream pic2) throws IOException, InvalidFormatException {
XmlCursor xmlCursor = currentParagraph.getCTP().newCursor();
xmlCursor.toNextSibling();
final XWPFParagraph paragraph = docx.insertNewParagraph(xmlCursor);
paragraph.setAlignment(ParagraphAlignment.CENTER);
final XWPFRun run1 = paragraph.createRun();
run1.addPicture(pic1, XWPFDocument.PICTURE_TYPE_PNG, "", Units.toEMU(205.208), Units.toEMU(153.906));
run1.addPicture(pic2, XWPFDocument.PICTURE_TYPE_PNG, "", Units.toEMU(205.208), Units.toEMU(153.906));
return paragraph;
}
public static XWPFParagraph insertParagraphAfter(XWPFDocument docx, XWPFParagraph currentParagraph) {
XmlCursor xmlCursor = currentParagraph.getCTP().newCursor();
xmlCursor.toNextSibling();
return docx.insertNewParagraph(xmlCursor);
}
public static XWPFParagraph insertParagraphAfter(XWPFDocument docx, XmlCursor xmlCursor) {
xmlCursor.toNextSibling();
return docx.insertNewParagraph(xmlCursor);
}
public static XWPFParagraph insertParagraphAfter(XWPFDocument docx, XWPFTable xwpfTable) {
XmlCursor xmlCursor = xwpfTable.getCTTbl().newCursor();
xmlCursor.toNextSibling();
return docx.insertNewParagraph(xmlCursor);
}
public static XWPFTable insertTableAfter(XWPFDocument docx, XWPFParagraph currentParagraph) {
XmlCursor xmlCursor = currentParagraph.getCTP().newCursor();
xmlCursor.toNextSibling();
return docx.insertNewTbl(xmlCursor);
}
public static XWPFTable insertTableAfter(XWPFDocument docx, XWPFTable xwpfTable) {
XmlCursor xmlCursor = xwpfTable.getCTTbl().newCursor();
xmlCursor.toNextSibling();
return docx.insertNewTbl(xmlCursor);
}
/**
* 移除paragraph中所有的run,不保留run
*
* @param paragraph
*/
public static void clearMe(XWPFParagraph paragraph) {
for (int i = paragraph.getRuns().size(); i > 0; i--) {
paragraph.removeRun(0);
}
}
/**
* 把自己移除
*
* @param paragraph
*/
public static void removeMe(XWPFParagraph paragraph) {
final XWPFDocument document = paragraph.getDocument();
}
/**
* 简单的设置字体和字号,为run设置
*
* @param run
* @param fontSizeMutiply2 字号*2 比如要设置10.5号字,就传入21
* @param englishFont Nullable
* @param chineseFont Nullable
*/
public static void setFontAndSize(XWPFRun run, int fontSizeMutiply2, String englishFont, String chineseFont) {
//todo set color
run.setColor(POIColor.BLUE.toString());
//给字体赋值,避免设置字体时出现null
run.setFontFamily("Times New Roman");
//给字号赋值,避免设置字号时出现null
run.setFontSize(9);
//这地方 因为fontSize不存在小数点,所以很蛋疼,这里的BigInteger是fontSize*2,看源码即可知道。
run.getCTR().getRPr().getSz().setVal(new BigInteger(fontSizeMutiply2 + ""));
//设置英文字体
run.getCTR().getRPr().getRFonts().setAscii(englishFont == null ? "Times New Roman" : englishFont);
//设置中文字体
run.getCTR().getRPr().getRFonts().setEastAsia(chineseFont == null ? "宋体" : chineseFont);
}
}
package cn.wise.sc.energy.power.plant.business.poi;
package cn.wise.sc.energy.power.plant.business.utils.poi;
import cn.afterturn.easypoi.word.WordExportUtil;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
......@@ -7,7 +7,7 @@ import java.io.File;
import java.io.FileOutputStream;
import java.util.Map;
public class WordUtil {
public class WordUtils {
/**
* 导出word
* <p>第一步生成替换后的word文件,只支持docx</p>
......
package cn.wise.sc.energy.power.plant.business.utils.poi.styles;
public interface FieldCodes {
String PIC_DEFAULT = "SEQ 图 \\* ARABIC";
String TABLE_DEFAULT = "SEQ 表 \\* ARABIC";
}
package cn.wise.sc.energy.power.plant.business.utils.poi.styles;
public class POIColor {
/**
* 颜色的HEX值,例c71d24
*/
private String rgbStr;
private POIColor(String rgbStr) {
this.rgbStr = rgbStr;
}
@Override
public String toString(){
return rgbStr;
}
/**
* 浅粉色
*/
public static final POIColor LIGHTPINK=new POIColor("FFB6C1");
/**
* 粉红
*/
public static final POIColor PINK=new POIColor("FFC0CB");
/**
* 猩红
*/
public static final POIColor CRIMSON=new POIColor("DC143C");
/**
* 脸红的淡紫色
*/
public static final POIColor LAVENDERBLUSH=new POIColor("FFF0F5");
/**
* 苍白的紫罗兰红色
*/
public static final POIColor PALEVIOLETRED=new POIColor("DB7093");
/**
* 热情的粉红
*/
public static final POIColor HOTPINK=new POIColor("FF69B4");
/**
* 深粉色
*/
public static final POIColor DEEPPINK=new POIColor("FF1493");
/**
* 适中的紫罗兰红色
*/
public static final POIColor MEDIUMVIOLETRED=new POIColor("C71585");
/**
* 兰花的紫色
*/
public static final POIColor ORCHID=new POIColor("DA70D6");
/**
* 蓟
*/
public static final POIColor THISTLE=new POIColor("D8BFD8");
/**
* 李子
*/
public static final POIColor PLUM=new POIColor("DDA0DD");
/**
* 紫罗兰
*/
public static final POIColor VIOLET=new POIColor("EE82EE");
/**
* 洋红
*/
public static final POIColor MAGENTA=new POIColor("FF00FF");
/**
* 灯笼海棠(紫红色)
*/
public static final POIColor FUCHSIA=new POIColor("FF00FF");
/**
* 深洋红色
*/
public static final POIColor DARKMAGENTA=new POIColor("8B008B");
/**
* 紫色
*/
public static final POIColor PURPLE=new POIColor("800080");
/**
* 适中的兰花紫
*/
public static final POIColor MEDIUMORCHID=new POIColor("BA55D3");
/**
* 深紫罗兰色
*/
public static final POIColor DARKVOILET=new POIColor("9400D3");
/**
* 深兰花紫
*/
public static final POIColor DARKORCHID=new POIColor("9932CC");
/**
* 靛青
*/
public static final POIColor INDIGO=new POIColor("4B0082");
/**
* 深紫罗兰的蓝色
*/
public static final POIColor BLUEVIOLET=new POIColor("8A2BE2");
/**
* 适中的紫色
*/
public static final POIColor MEDIUMPURPLE=new POIColor("9370DB");
/**
* 适中的板岩暗蓝灰色
*/
public static final POIColor MEDIUMSLATEBLUE=new POIColor("7B68EE");
/**
* 板岩暗蓝灰色
*/
public static final POIColor SLATEBLUE=new POIColor("6A5ACD");
/**
* 深岩暗蓝灰色
*/
public static final POIColor DARKSLATEBLUE=new POIColor("483D8B");
/**
* 薰衣草花的淡紫色
*/
public static final POIColor LAVENDER=new POIColor("E6E6FA");
/**
* 幽灵的白色
*/
public static final POIColor GHOSTWHITE=new POIColor("F8F8FF");
/**
* 纯蓝
*/
public static final POIColor BLUE = new POIColor("1E0FB1");
/**
* 适中的蓝色
*/
public static final POIColor MEDIUMBLUE=new POIColor("0000CD");
/**
* 午夜的蓝色
*/
public static final POIColor MIDNIGHTBLUE=new POIColor("191970");
/**
* 深蓝色
*/
public static final POIColor DARKBLUE=new POIColor("00008B");
/**
* 海军蓝
*/
public static final POIColor NAVY=new POIColor("000080");
/**
* 宝蓝
*/
public static final POIColor ROYALBLUE=new POIColor("4169E1");
/**
* 矢车菊的蓝色
*/
public static final POIColor CORNFLOWERBLUE=new POIColor("6495ED");
/**
* 淡钢蓝
*/
public static final POIColor LIGHTSTEELBLUE=new POIColor("B0C4DE");
/**
* 浅石板灰
*/
public static final POIColor LIGHTSLATEGRAY=new POIColor("778899");
/**
* 石板灰
*/
public static final POIColor SLATEGRAY=new POIColor("708090");
/**
* 道奇蓝
*/
public static final POIColor DODERBLUE=new POIColor("1E90FF");
/**
* 爱丽丝蓝
*/
public static final POIColor ALICEBLUE=new POIColor("F0F8FF");
/**
* 钢蓝
*/
public static final POIColor STEELBLUE=new POIColor("4682B4");
/**
* 淡蓝色
*/
public static final POIColor LIGHTSKYBLUE=new POIColor("87CEFA");
/**
* 天蓝色
*/
public static final POIColor SKYBLUE=new POIColor("87CEEB");
/**
* 深天蓝
*/
public static final POIColor DEEPSKYBLUE=new POIColor("00BFFF");
/**
* 淡蓝
*/
public static final POIColor LIGHTBLUE=new POIColor("ADD8E6");
/**
* 火药蓝
*/
public static final POIColor POWDERBLUE=new POIColor("B0E0E6");
/**
* 军校蓝
*/
public static final POIColor CADETBLUE=new POIColor("5F9EA0");
/**
* 蔚蓝色
*/
public static final POIColor AZURE=new POIColor("F0FFFF");
/**
* 淡青色
*/
public static final POIColor LIGHTCYAN=new POIColor("E1FFFF");
/**
* 苍白的绿宝石
*/
public static final POIColor PALETURQUOISE=new POIColor("AFEEEE");
/**
* 青色
*/
public static final POIColor CYAN=new POIColor("00FFFF");
/**
* 水绿色
*/
public static final POIColor AQUA=new POIColor("00FFFF");
/**
* 深绿宝石
*/
public static final POIColor DARKTURQUOISE=new POIColor("00CED1");
/**
* 深石板灰
*/
public static final POIColor DARKSLATEGRAY=new POIColor("2F4F4F");
/**
* 深青色
*/
public static final POIColor DARKCYAN=new POIColor("008B8B");
/**
* 水鸭色
*/
public static final POIColor TEAL=new POIColor("008080");
/**
* 适中的绿宝石
*/
public static final POIColor MEDIUMTURQUOISE=new POIColor("48D1CC");
/**
* 浅海洋绿
*/
public static final POIColor LIGHTSEAGREEN=new POIColor("20B2AA");
/**
* 绿宝石
*/
public static final POIColor TURQUOISE=new POIColor("40E0D0");
/**
* 绿玉
*/
public static final POIColor BABYGREEN=new POIColor("7FFFAA");
/**
* 适中的碧绿色
*/
public static final POIColor MEDIUMAQUAMARINE=new POIColor("00FA9A");
/**
* 适中的春天的绿色
*/
public static final POIColor MEDIUMSPRINGGREEN=new POIColor("F5FFFA");
/**
* 薄荷奶油
*/
public static final POIColor MINTCREAM=new POIColor("00FF7F");
/**
* 春天的绿色
*/
public static final POIColor SPRINGGREEN=new POIColor("3CB371");
/**
* 海洋绿
*/
public static final POIColor SEAGREEN=new POIColor("2E8B57");
/**
* 蜂蜜
*/
public static final POIColor HONEYDEW=new POIColor("F0FFF0");
/**
* 淡绿色
*/
public static final POIColor LIGHTGREEN=new POIColor("90EE90");
/**
* 苍白的绿色
*/
public static final POIColor PALEGREEN=new POIColor("98FB98");
/**
* 深海洋绿
*/
public static final POIColor DARKSEAGREEN=new POIColor("8FBC8F");
/**
* 酸橙绿
*/
public static final POIColor LIMEGREEN=new POIColor("32CD32");
/**
* 酸橙色
*/
public static final POIColor LIME=new POIColor("00FF00");
/**
* 森林绿
*/
public static final POIColor FORESTGREEN=new POIColor("228B22");
/**
* 纯绿
*/
public static final POIColor GREEN=new POIColor("008000");
/**
* 深绿色
*/
public static final POIColor DARKGREEN=new POIColor("006400");
/**
* 查特酒绿
*/
public static final POIColor CHARTREUSE=new POIColor("7FFF00");
/**
* 草坪绿
*/
public static final POIColor LAWNGREEN=new POIColor("7CFC00");
/**
* 绿黄色
*/
public static final POIColor GREENYELLOW=new POIColor("ADFF2F");
/**
* 橄榄土褐色
*/
public static final POIColor OLIVEDRAB=new POIColor("556B2F");
/**
* 米色(浅褐色)
*/
public static final POIColor BEIGE=new POIColor("6B8E23");
/**
* 浅秋麒麟黄
*/
public static final POIColor LIGHTGOLDENRODYELLOW=new POIColor("FAFAD2");
/**
* 象牙色
*/
public static final POIColor IVORY=new POIColor("FFFFF0");
/**
* 浅黄色
*/
public static final POIColor LIGHTYELLOW=new POIColor("FFFFE0");
/**
* 纯黄
*/
public static final POIColor YELLOW=new POIColor("FFFF00");
/**
* 橄榄
*/
public static final POIColor OLIVE=new POIColor("808000");
/**
* 深卡其布
*/
public static final POIColor DARKKHAKI=new POIColor("BDB76B");
/**
* 柠檬薄纱
*/
public static final POIColor LEMONCHIFFON=new POIColor("FFFACD");
/**
* 灰秋麒麟
*/
public static final POIColor PALEGODENROD=new POIColor("EEE8AA");
/**
* 卡其布
*/
public static final POIColor KHAKI=new POIColor("F0E68C");
/**
* 金
*/
public static final POIColor GOLD=new POIColor("FFD700");
/**
* 玉米色
*/
public static final POIColor CORNISLK=new POIColor("FFF8DC");
/**
* 秋麒麟
*/
public static final POIColor GOLDENROD=new POIColor("DAA520");
/**
* 花的白色
*/
public static final POIColor FLORALWHITE=new POIColor("FFFAF0");
/**
* 老饰带
*/
public static final POIColor OLDLACE=new POIColor("FDF5E6");
/**
* 小麦色
*/
public static final POIColor WHEAT=new POIColor("F5DEB3");
/**
* 鹿皮鞋
*/
public static final POIColor MOCCASIN=new POIColor("FFE4B5");
/**
* 橙色
*/
public static final POIColor ORANGE=new POIColor("FFA500");
/**
* 番木瓜
*/
public static final POIColor PAPAYAWHIP=new POIColor("FFEFD5");
/**
* 漂白的杏仁
*/
public static final POIColor BLANCHEDALMOND=new POIColor("FFEBCD");
/**
* Navajo白
*/
public static final POIColor NAVAJOWHITE=new POIColor("FFDEAD");
/**
* 古代的白色
*/
public static final POIColor ANTIQUEWHITE=new POIColor("FAEBD7");
/**
* 晒黑
*/
public static final POIColor TAN=new POIColor("D2B48C");
/**
* 结实的树
*/
public static final POIColor BRULYWOOD=new POIColor("DEB887");
/**
* (浓汤)乳脂,番茄等
*/
public static final POIColor BISQUE=new POIColor("FFE4C4");
/**
* 深橙色
*/
public static final POIColor DARKORANGE=new POIColor("FF8C00");
/**
* 亚麻布
*/
public static final POIColor LINEN=new POIColor("FAF0E6");
/**
* 秘鲁
*/
public static final POIColor PERU=new POIColor("CD853F");
/**
* 桃色
*/
public static final POIColor PEACHPUFF=new POIColor("FFDAB9");
/**
* 沙棕色
*/
public static final POIColor SANDYBROWN=new POIColor("F4A460");
/**
* 巧克力
*/
public static final POIColor CHOCOLATE=new POIColor("D2691E");
/**
* 马鞍棕色
*/
public static final POIColor SADDLEBROWN=new POIColor("8B4513");
/**
* 海贝壳
*/
public static final POIColor SEASHELL=new POIColor("FFF5EE");
/**
* 黄土赭色
*/
public static final POIColor SIENNA=new POIColor("A0522D");
/**
* 浅鲜肉(鲑鱼)色
*/
public static final POIColor LIGHTSALMON=new POIColor("FFA07A");
/**
* 珊瑚
*/
public static final POIColor CORAL=new POIColor("FF7F50");
/**
* 橙红色
*/
public static final POIColor ORANGERED=new POIColor("FF4500");
/**
* 深鲜肉(鲑鱼)色
*/
public static final POIColor DARKSALMON=new POIColor("E9967A");
/**
* 番茄
*/
public static final POIColor TOMATO=new POIColor("FF6347");
/**
* 薄雾玫瑰
*/
public static final POIColor MISTYROSE=new POIColor("FFE4E1");
/**
* 鲜肉(鲑鱼)色
*/
public static final POIColor SALMON=new POIColor("FA8072");
/**
* 雪
*/
public static final POIColor SNOW=new POIColor("FFFAFA");
/**
* 淡珊瑚色
*/
public static final POIColor LIGHTCORAL=new POIColor("F08080");
/**
* 玫瑰棕色
*/
public static final POIColor ROSYBROWN=new POIColor("BC8F8F");
/**
* 印度红
*/
public static final POIColor INDIANRED=new POIColor("CD5C5C");
/**
* 纯红
*/
public static final POIColor RED=new POIColor("FF0000");
/**
* 棕色
*/
public static final POIColor BROWN=new POIColor("A52A2A");
/**
* 耐火砖
*/
public static final POIColor FIREBRICK=new POIColor("B22222");
/**
* 深红色
*/
public static final POIColor DARKRED=new POIColor("8B0000");
/**
* 栗色
*/
public static final POIColor MAROON=new POIColor("800000");
/**
* 纯白
*/
public static final POIColor WHITE=new POIColor("FFFFFF");
/**
* 白烟
*/
public static final POIColor WHITESMOKE=new POIColor("F5F5F5");
/**
* Gainsboro
*/
public static final POIColor GAINSBORO=new POIColor("DCDCDC");
/**
* 浅灰色
*/
public static final POIColor LIGHTGRAY=new POIColor("D3D3D3");
/**
* 银白色
*/
public static final POIColor SILVER=new POIColor("C0C0C0");
/**
* 深灰色
*/
public static final POIColor DARKGRAY=new POIColor("A9A9A9");
/**
* 灰色
*/
public static final POIColor GRAY=new POIColor("808080");
/**
* 暗淡的灰色
*/
public static final POIColor DIMGRAY=new POIColor("696969");
/**
* 纯黑
*/
public static final POIColor BLACK=new POIColor("000000");
}
package cn.wise.sc.energy.power.plant.business.utils.poi.styles;
import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
import org.apache.poi.xwpf.usermodel.VerticalAlign;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import java.math.BigInteger;
public class Style {
/**
* 居中格式
*/
private ParagraphAlignment alignment;
/**
* 表格上下居中,无法在run设置
*/
// private XWPFTableCell.XWPFVertAlign verticalAlignment;
/**
* 段前间距 磅值
*/
private Double spaceBefore;
/**
* 行距 磅值
*/
private Double spaceBetween;
/**
* 段后间距 磅值
*/
private Double spaceAfter;
/**
* 字号
*/
private Integer fontSizeMutiply2;
/**
* 西文字体
*/
private String englishFont;
/**
* 中文字体
*/
private String chineseFont;
/**
* 颜色
*/
private POIColor color;
/**
* 首行缩进
*/
private Integer indentationFirstLine;
/**
* 悬挂缩进
*/
private Integer hang;
/**
* 加粗
* true加粗
* false不加粗
*/
private boolean bold;
/**
* 上下标控制
* VerticalAlign.BASELINE: 正常;
* VerticalAlign.SUPERSCRIPT: 上标;
* VerticalAlign.SUBSCRIPT: 下标.
*/
private VerticalAlign verticalAlign;
public static Style TITLE_STYLE = new Style(
ParagraphAlignment.LEFT,
0d,
1d,
0d,
32,
"Times New Roman",
"宋体",
POIColor.BLUE,
VerticalAlign.BASELINE,
0, null, true);
public static Style WARNING_TITLE_STYLE = new Style(
ParagraphAlignment.CENTER,
0d,
1d,
0d,
32,
"Times New Roman",
"宋体",
POIColor.RED,
VerticalAlign.BASELINE,
0, null, true);
public static final Style DEFAULT_PARA_STYLE = new Style(
//BOTH为分散对齐
ParagraphAlignment.BOTH,
0.5,
1.5d,
0.5,
21,
"Times New Roman",
"宋体",
POIColor.BLUE,
VerticalAlign.BASELINE,
420, null, false);
public static final Style DEFAULT_PARA_LIGHT_STYLE = new Style(
ParagraphAlignment.BOTH,
0.5,
1.5d,
0.5,
21,
"Times New Roman",
"宋体",
POIColor.RED,
VerticalAlign.BASELINE,
420, null, false);
public static final Style DEFAULT_TABLE_CONTENT_STYLE = new Style(
ParagraphAlignment.CENTER,
0d,
1.5d,
0d,
16,
"Times New Roman",
"宋体",
POIColor.BLUE,
VerticalAlign.BASELINE,
null, null, false);
public static final Style ELEC_TABLE_CONTENT_STYLE = new Style(
ParagraphAlignment.CENTER,
0.5,
1.5d,
0.5,
18,
"Times New Roman",
"宋体",
POIColor.BLUE,
VerticalAlign.BASELINE,
null, null, false);
public static final Style REVIEW_TABLE_CONTENT_STYLE = new Style(
ParagraphAlignment.CENTER,
null,
1.5d,
null,
18,
"宋体",
"宋体",
POIColor.BLUE,
VerticalAlign.BASELINE,
null, null, false);
public static final Style WARNING_CONTENT_STYLE = new Style(
ParagraphAlignment.CENTER,
0.5,
1.5d,
0.5,
18,
"宋体",
"宋体",
POIColor.RED,
VerticalAlign.BASELINE,
null, null, false);
public static final Style DEFAULT_TABLE_CONTENT_SUPER_STYLE = new Style(
ParagraphAlignment.CENTER,
null,
1.5d,
null,
18,
"Times New Roman",
"宋体",
POIColor.BLUE,
VerticalAlign.SUPERSCRIPT,
null, null, false);
public static final Style DEFAULT_TABLE_CONTENT_LIGHT_STYLE = new Style(
ParagraphAlignment.CENTER,
0d,
1.5d,
0d,
18,
"Times New Roman",
"宋体",
POIColor.RED,
VerticalAlign.BASELINE,
null, null, false);
public static final Style REVIEW_TABLE_CONTENT_LIGHT_STYLE = new Style(
ParagraphAlignment.CENTER,
null,
1.5d,
null,
18,
"宋体",
"宋体",
POIColor.RED,
VerticalAlign.BASELINE,
null, null, false);
public static final Style DEFAULT1_TABLE_CONTENT_STYLE = new Style(
ParagraphAlignment.CENTER,
null,
1.5d,
null,
18,
"Times New Roman",
"宋体",
POIColor.BLUE,
VerticalAlign.BASELINE,
null, null, false);
public static final Style DEFAULT2_TABLE_CONTENT_STYLE = new Style(
ParagraphAlignment.CENTER,
null,
1.5d,
null,
18,
"Times New Roman",
"宋体",
POIColor.RED,
VerticalAlign.BASELINE,
null, null, false);
public static final Style DEFAULT_TABLE_CONTENT_LIGHT_SUPER_STYLE = new Style(
ParagraphAlignment.CENTER,
null,
1.5d,
null,
18,
"Times New Roman",
"宋体",
POIColor.RED,
VerticalAlign.SUPERSCRIPT,
null, null, false);
public static final Style DEFAULT_TABLE_PIC_NAME_STYLE = new Style(
ParagraphAlignment.CENTER,
0.5d,
1.5d,
0.5d,
18,
"Times New Roman",
"宋体",
POIColor.BLUE,
VerticalAlign.BASELINE,
null, null, false);
public static final Style REVIEW_TABLE_PIC_NAME_STYLE = new Style(
ParagraphAlignment.CENTER,
0.5d,
1.5d,
0.5d,
18,
"宋体",
"宋体",
POIColor.BLUE,
VerticalAlign.BASELINE,
null, null, false);
public static final Style BLACK_FONT_TABLE_PIC_NAME_STYLE = new Style(
ParagraphAlignment.CENTER,
0.5d,
1.5d,
0.5d,
21,
"Times New Roman",
"黑体",
POIColor.BLUE,
VerticalAlign.BASELINE,
null, null, false);
public static final Style TABLE_COMMENT = new Style(
ParagraphAlignment.LEFT,
0d,
1d,
0d,
18,
"Times New Roman",
"宋体",
POIColor.BLUE,
VerticalAlign.BASELINE,
null, null, false);
private Style() {
}
public Style(ParagraphAlignment alignment,
Double spaceBefore,
Double spaceBetween,
Double spaceAfter,
Integer fontSizeMutiply2,
String englishFont,
String chineseFont,
POIColor color,
VerticalAlign verticalAlign,
Integer indentationFirstLine,
Integer hang,
boolean bold) {
this.alignment = alignment;
this.spaceBefore = spaceBefore;
this.spaceBetween = spaceBetween;
this.spaceAfter = spaceAfter;
this.fontSizeMutiply2 = fontSizeMutiply2;
this.englishFont = englishFont;
this.chineseFont = chineseFont;
this.color = color;
this.verticalAlign = verticalAlign;
this.indentationFirstLine = indentationFirstLine;
this.hang = hang;
this.bold = bold;
}
public Integer getHang() {
return hang;
}
public void setHang(Integer hang) {
this.hang = hang;
}
public Integer getIndentationFirstLine() {
return indentationFirstLine;
}
public void setIndentationFirstLine(int indentationFirstLine) {
this.indentationFirstLine = indentationFirstLine;
}
public VerticalAlign getVerticalAlign() {
return verticalAlign;
}
public void setVerticalAlign(VerticalAlign verticalAlign) {
this.verticalAlign = verticalAlign;
}
public void setSpaceBetween(Double spaceBetween) {
this.spaceBetween = spaceBetween;
}
public void setFontSizeMutiply2(Integer fontSizeMutiply2) {
this.fontSizeMutiply2 = fontSizeMutiply2;
}
public ParagraphAlignment getAlignment() {
return alignment;
}
public void setAlignment(ParagraphAlignment alignment) {
this.alignment = alignment;
}
public Double getSpaceBetween() {
return spaceBetween;
}
public int getFontSizeMutiply2() {
return fontSizeMutiply2;
}
public void setFontSizeMutiply2(int fontSizeMutiply2) {
this.fontSizeMutiply2 = fontSizeMutiply2;
}
public String getEnglishFont() {
return englishFont;
}
public void setEnglishFont(String englishFont) {
this.englishFont = englishFont;
}
public String getChineseFont() {
return chineseFont;
}
public void setChineseFont(String chineseFont) {
this.chineseFont = chineseFont;
}
public POIColor getColor() {
return color;
}
public void setColor(POIColor color) {
this.color = color;
}
public Double getSpaceBefore() {
return spaceBefore;
}
public void setSpaceBefore(Double spaceBefore) {
this.spaceBefore = spaceBefore;
}
public Double getSpaceAfter() {
return spaceAfter;
}
public void setSpaceAfter(Double spaceAfter) {
this.spaceAfter = spaceAfter;
}
public void setIndentationFirstLine(Integer indentationFirstLine) {
this.indentationFirstLine = indentationFirstLine;
}
public void proccess(XWPFRun run) {
if (alignment != null) {
//skip
}
if (spaceBetween != null) {
//skip
}
if (fontSizeMutiply2 != null) {
run.setFontSize(9);
run.getCTR().getRPr().getSz().setVal(new BigInteger(fontSizeMutiply2 + ""));
}
if (verticalAlign != null) {
run.setSubscript(verticalAlign);
}
run.setBold(bold);
//给字体赋值,避免设置字体时出现null
run.setFontFamily("Times New Roman");
run.getCTR().getRPr().getRFonts().setAscii(englishFont == null ? "Times New Roman" : englishFont);
run.getCTR().getRPr().getRFonts().setEastAsia(chineseFont == null ? "宋体" : chineseFont);
if (color != null) {
run.setColor(color.toString());
}
}
/**
* 对于段落的处理总共有如下几种格式:
* 居中类型:
* 段前间距:word中为磅值
* 行距:word中为倍数
* 段后间距:word中为磅值
* 首行缩进:
*
* @param paragraph
*/
public void proccess(XWPFParagraph paragraph) {
if (alignment != null) {
paragraph.setAlignment(alignment);
}
if (spaceBefore != null) {
int value = (int) (spaceBefore / 0.05);
//按照行来设置的优先级更高,如果不设置为0,则磅值会被覆盖
paragraph.setSpacingBeforeLines(0);
paragraph.setSpacingBefore(value);
}
if (spaceBetween != null) {
paragraph.setSpacingBetween(spaceBetween);
}
if (spaceAfter != null) {
int value = (int) (spaceAfter / 0.05);
//按照行来设置的优先级更高,如果不设置为0,则磅值会被覆盖,如果设置afterLines为80,则代表0.8行。
paragraph.setSpacingAfterLines(0);
paragraph.setSpacingAfter(value);
}
if (indentationFirstLine != null) {
paragraph.setIndentationFirstLine(indentationFirstLine);
} else if (hang != null) {
paragraph.setIndentationHanging(hang);
} else {
paragraph.setIndentationFirstLine(0);
}
for (XWPFRun run : paragraph.getRuns()) {
this.proccess(run);
}
}
}
package cn.wise.sc.energy.power.plant.business.utils.poi.xwpftable;
import cn.wise.sc.energy.power.plant.business.utils.poi.styles.Style;
import javax.validation.constraints.NotNull;
import java.util.LinkedList;
import java.util.List;
/**
* @author qilei
* @since 2018-05-15 13:45
*/
public class ToolXWPFCell {
/**
* 中间的字符串随便填只要不跟真的文档重复就行了,这个字符应当不会重复的吧。
*/
public final static ToolXWPFCell CONTINUE = new ToolXWPFCell("{{emptyCell");
private List<ToolXwpfRun> runs;
public ToolXWPFCell(String content) {
runs = new LinkedList<>();
runs.add(new ToolXwpfRun(content));
}
public ToolXWPFCell(String content, @NotNull Style style) {
runs = new LinkedList<>();
runs.add(new ToolXwpfRun(content, style));
}
public ToolXWPFCell(ToolXwpfRun... runs) {
this.runs = new LinkedList<>();
for (int i = 0; i < runs.length; i++) {
this.runs.add(new ToolXwpfRun(runs[i].getContent(), runs[i].getStyle()));
}
}
public List<ToolXwpfRun> getRuns() {
return runs;
}
public void setRuns(List<ToolXwpfRun> runs) {
this.runs = runs;
}
}
package cn.wise.sc.energy.power.plant.business.utils.poi.xwpftable;
import cn.wise.sc.energy.power.plant.business.utils.poi.styles.Style;
/**
* @author qilei
* @since 2018-05-22 08:57
* todo 实现深拷贝
*/
public class ToolXwpfRun {
private String content;
private Style style;
public ToolXwpfRun(String content, Style style) {
this.content = content;
this.style = style;
}
public ToolXwpfRun(String content) {
this.content = content;
this.style = Style.DEFAULT_TABLE_CONTENT_STYLE;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Style getStyle() {
return style;
}
public void setStyle(Style style) {
this.style = style;
}
}
......@@ -96,7 +96,7 @@ spring:
# max-idle-per-key: 10
# #每个key对应的连接池最小空闲连接数
# max_idle_per_key: 5
jpa:
jpa:
hibernate:
naming:
physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
......
......@@ -49,7 +49,7 @@
<maxFileSize>100MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<!--日志文档保留天数-->
<maxHistory>15</maxHistory>
<maxHistory>1</maxHistory>
</rollingPolicy>
<!-- 此日志文档只记录debug级别的 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
......@@ -179,7 +179,7 @@
<logger name="cn.wise.sc.cement.business.controller" level="debug"/><!-- 修改此处扫描包名 -->
</springProfile>
<root level="debug">
<root level="error">
<appender-ref ref="CONSOLE" />
<appender-ref ref="DEBUG_FILE" />
<appender-ref ref="INFO_FILE" />
......@@ -189,7 +189,7 @@
<!--4.2 生产环境:输出到文档-->
<springProfile name="pro">
<root level="info">
<root level="debug">
<appender-ref ref="CONSOLE" />
<appender-ref ref="DEBUG_FILE" />
<appender-ref ref="INFO_FILE" />
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment