Commit e2803cca authored by KeYong's avatar KeYong

更新

# Conflicts: # amos-boot-system-equip/src/main/resources/changelog/wl-3.6.0.xml
parent 128a579d
package com.yeejoin.equipmanage.common.dto;
import cn.afterturn.easypoi.excel.annotation.Excel;
import cn.afterturn.easypoi.excel.annotation.ExcelIgnore;
import lombok.Data;
import java.util.Date;
/**
* @author keyong
* @title: FaultCaseImportParam
* <pre>
* @description: TODO
* </pre>
* @date 2023/10/31 17:27
*/
@Data
public class FaultCaseImportParam {
@ExcelIgnore
private Date createDate;
@Excel(name = "消防系统", orderNum = "0")
private String systemInfo;
@Excel(name = "部件id", orderNum = "1")
private String equipId;
@Excel(name = "故障类型", orderNum = "2")
private String faultType;
@Excel(name = "故障等级", orderNum = "3")
private String faultLevel;
@Excel(name = "故障描述", orderNum = "4")
private String faultDescribe;
@Excel(name = "处理建议", orderNum = "5")
private String handleAdvise;
@Excel(name = "故障影响", orderNum = "6")
private String faultEffect;
@Excel(name = "预防措施", orderNum = "7")
private String preventiveMeasure;
}
package com.yeejoin.equipmanage.common.entity;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import com.yeejoin.equipmanage.common.entity.publics.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
* 信号分类量测枚举表
*
* @author system_generator
* @date 2023-02-18
*/
@Data
@EqualsAndHashCode(callSuper = true)
@Accessors(chain = true)
@TableName("wl_fault_case")
public class FaultCase extends BaseEntity {
private static final long serialVersionUID = 1L;
/**
* 主键
*/
@TableField("id")
private Long id;
/**
* 系统id
*/
@TableField("system_id")
private String systemId;
/**
* 系统编码
*/
@TableField("system_type_code")
private String systemTypeCode;
/**
* 系统名称
*/
@TableField("system_name")
private String systemName;
/**
* 部件id
*/
@TableField("equip_id")
private String equipId;
/**
* 部件名称
*/
@TableField("equip_name")
private String equipName;
/**
* 故障等级
*/
@TableField("fault_level")
private String faultLevel;
/**
* 故障类型
*/
@TableField("fault_type")
private String faultType;
/**
* 故障描述
*/
@TableField("fault_describe")
private String faultDescribe;
/**
* 处理建议
*/
@TableField("handle_advise")
private String handleAdvise;
/**
* 故障影响
*/
@TableField("fault_effect")
private String faultEffect;
/**
* 预防措施
*/
@TableField("preventive_measure")
private String preventiveMeasure;
@TableField(exist = false)
private String searchName;
}
package com.yeejoin.equipmanage.common.enums;
import lombok.AllArgsConstructor;
import lombok.Getter;
import java.util.ArrayList;
import java.util.List;
/**
* 类型枚举
* @author DELL
*/
@Getter
@AllArgsConstructor
public enum EmergencyLevelEum {
JJ("1", "紧急"),
YZ("2", "严重"),
QW("3", "轻微"),
ZC("4", "正常"),
WX("5", "无效"),
BY("6", "备用"),
QT("7", "其他");
private String code;
private String name;
public static List<String> getDropDownList() {
List<String> list = new ArrayList<>();
for(EmergencyLevelEum eum : EmergencyLevelEum.values()) {
String str = eum.getName() + "@" + eum.getCode();
list.add(str);
}
return list;
}
public static String getNameByCode(String code) {
String str = null;
for(EmergencyLevelEum eum : EmergencyLevelEum.values()) {
if (code.equalsIgnoreCase(eum.getCode())) {
str = eum.getName();
break;
}
}
return str;
}
}
package com.yeejoin.amos.boot.module.jcs.api.dto;
import com.alibaba.excel.annotation.ExcelIgnore;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
......
......@@ -7,6 +7,7 @@ import com.yeejoin.amos.boot.module.jcs.api.entity.Sign;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
/**
......@@ -22,6 +23,8 @@ public interface SignMapper extends BaseMapper<Sign> {
IPage<SinStaticDto> queryStaticForPage(IPage<?> page, SinStaticDto dto);
List<Map<String, Object>> queryPeopleInfo(SinStaticDto dto);
int queryPersonNum(String bizOgrCode);
// Map<String, Object> getSignStatistic(@Param("bizOrgCode") String bizOgrCode, @Param("userId") String userId);
......
......@@ -75,6 +75,58 @@
sign.sign_time desc
) s group by date,bizOrgCode
</select>
<select id="queryPeopleInfo" resultType="Map">
SELECT
s1.date,
IFNULL( s2.signNum, 0 ) AS signNum
FROM
(
SELECT
@s := @s + 1 AS `index`,
DATE_FORMAT( DATE_ADD(( DATE( DATE_ADD( now(), INTERVAL - 5 DAY ))), INTERVAL @s DAY ), '%Y-%m-%d' ) AS date
FROM
mysql.help_topic,
( SELECT @s := - 2 ) temp
WHERE
@s &lt; 5
) s1
LEFT JOIN (
SELECT
count(userId) signNum,
s.*
FROM
(
SELECT
DISTINCT sign.user_id userId,
date,
biz_org_Name bizOrgName,
biz_org_code bizOrgCode,
person_of_day personOfDay
FROM
cb_sign sign
<where>
<if test="dto.dateLESS!=null and dto.dateLESS!=''">
and #{dto.dateLESS} >= sign.sign_time
</if>
<if test="dto.bizOrgCode!=null and dto.bizOrgCode!=''">
and sign.biz_org_code like CONCAT(#{dto.bizOrgCode},'%')
</if>
</where>
group by
date,
biz_org_code,
user_id
order by
sign.sign_time desc
) s
) s2 ON s2.date = s1.date
GROUP BY
s1.date
ORDER BY
s1.date
</select>
<select id="queryPersonNum" resultType="java.lang.Integer">
select count(*) from cb_firefighters where biz_org_code like CONCAT('%',#{bizOgrCode}, '%') AND people_type = '1601'
AND is_delete = 0 AND now() > rec_date
......
package com.yeejoin.equipmanage.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.equipmanage.common.dto.FaultCaseImportParam;
import com.yeejoin.equipmanage.common.entity.EquipmentSpecific;
import com.yeejoin.equipmanage.common.entity.FaultCase;
import com.yeejoin.equipmanage.common.entity.FireFightingSystemEntity;
import com.yeejoin.equipmanage.common.entity.SignalClassify;
import com.yeejoin.equipmanage.common.entity.publics.CommonResponse;
import com.yeejoin.equipmanage.common.entity.vo.EquiplistSpecificBySystemVO;
import com.yeejoin.equipmanage.common.enums.EmergencyLevelEum;
import com.yeejoin.equipmanage.common.utils.CommonResponseUtil;
import com.yeejoin.equipmanage.common.utils.StringUtil;
import com.yeejoin.equipmanage.service.IEquipmentSpecificSerivce;
import com.yeejoin.equipmanage.service.IFaultCaseService;
import com.yeejoin.equipmanage.service.IFireFightingSystemService;
import com.yeejoin.equipmanage.service.ISignalClassifyService;
import com.yeejoin.equipmanage.utils.FileHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import liquibase.pro.packaged.S;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* 信号分类量测枚举表
*
* @author system_generator
* @date 2022-02-18
*/
@RestController
@Api(tags = "信号分类量测枚举表Api")
@RequestMapping(value = "/fault/case", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class FaultCaseController extends AbstractBaseController {
@Autowired
IFaultCaseService faultCaseService;
@Autowired
ISignalClassifyService signalClassifyService;
@Autowired
IFireFightingSystemService fireFightingSystemService;
@Autowired
IEquipmentSpecificSerivce equipmentSpecificService;
/**
* 新增信号分类量测枚举表
*
* @return
*/
@TycloudOperation(ApiLevel = UserType.AGENCY)
@PostMapping(value = "/save")
@ApiOperation(httpMethod = "POST", value = "新增信号分类量测枚举表", notes = "新增信号分类量测枚举表")
public ResponseModel<FaultCase> save(@RequestBody FaultCase model) {
faultCaseService.save(model);
return ResponseHelper.buildResponse(model);
}
/**
* 根据id更新
*
* @param
* @return
*/
@TycloudOperation(ApiLevel = UserType.AGENCY)
@PutMapping(value = "/update")
@ApiOperation(httpMethod = "PUT", value = "根据id更新故障案例", notes = "根据id更新故障案例")
public ResponseModel<FaultCase> updateByIdWlFaultCase(@RequestBody FaultCase model) {
faultCaseService.updateById(model);
return ResponseHelper.buildResponse(model);
}
/**
* 根据id删除
*
* @param id 主键
* @return
*/
@TycloudOperation(ApiLevel = UserType.AGENCY)
@DeleteMapping(value = "/{id}")
@ApiOperation(httpMethod = "DELETE", value = "根据id删除故障案例", notes = "根据id删除故障案例")
public ResponseModel<Boolean> deleteOneById(HttpServletRequest request, @PathVariable(value = "id") Long id){
return ResponseHelper.buildResponse(faultCaseService.removeById(id));
}
/**
* 根据id查询
*
* @param id 主键
* @return
*/
@TycloudOperation(ApiLevel = UserType.AGENCY)
@GetMapping(value = "/{id}")
@ApiOperation(httpMethod = "GET",value = "根据id查询单个故障案例", notes = "根据id查询单个故障案例")
public ResponseModel<FaultCase> selectOne(@PathVariable Long id) {
return ResponseHelper.buildResponse(faultCaseService.getById(id));
}
/**
* 列表全部数据查询
*
* @return
*/
@TycloudOperation(ApiLevel = UserType.AGENCY)
@ApiOperation(httpMethod = "GET",value = "故障案例列表全部数据查询", notes = "故障案例列表全部数据查询")
@GetMapping(value = "/list")
public ResponseModel<List<FaultCase>> selectForList() {
return ResponseHelper.buildResponse(faultCaseService.query().list());
}
/**
* 列表全部数据查询
*
* @return
*/
@TycloudOperation(ApiLevel = UserType.AGENCY)
@ApiOperation(httpMethod = "GET",value = "故障案例列表全部数据查询", notes = "故障案例列表全部数据查询")
@GetMapping(value = "/page")
public Page<FaultCase> selectForList(Page page,
@RequestParam(value = "systemId",required = false) String systemId,
@RequestParam(value = "faultLevel",required = false) String faultLevel,
@RequestParam(value = "faultType",required = false) String faultType,
@RequestParam(value = "name",required = false) String name) {
FaultCase dto = new FaultCase();
dto.setSystemId(systemId);
dto.setFaultLevel(faultLevel);
dto.setFaultType(faultType);
dto.setSearchName(name);
return faultCaseService.listPage(page, dto);
}
/**
* 模板导出
*
* @return
*/
@TycloudOperation(ApiLevel = UserType.AGENCY)
@ApiOperation(httpMethod = "GET",value = "模板导出", notes = "模板导出")
@GetMapping(value = "/export")
public ResponseModel<List<FaultCase>> exportTemplate(HttpServletResponse response) {
String fileName = "故障案例模板.xls"; //模板名称
String[] handers = {"消防系统","部件id","故障类型","故障等级","故障描述","处理建议","故障影响","预防措施"}; //列标题
List<String[]> downData = new ArrayList();
List<FireFightingSystemEntity> systems = fireFightingSystemService.getList();
if(0 < systems.size()) {
List<String> sysList = new ArrayList<>();
for (FireFightingSystemEntity entity : systems) {
String str = entity.getName() + "@" + entity.getId() + "@" + entity.getSystemTypeCode();
sysList.add(str);
}
// 消防系统
downData.add(sysList.toArray(new String[sysList.size()]));
}
List<SignalClassify> singles = signalClassifyService.getList();
if(0 < singles.size()) {
List<String> classList = new ArrayList<>();
for (SignalClassify signalClassify : singles) {
String str = signalClassify.getTypeName();
classList.add(str);
}
// 故障类型
downData.add(classList.toArray(new String[classList.size()]));
}
// 故障等级
List<String> levels = EmergencyLevelEum.getDropDownList();
downData.add(levels.toArray(new String[levels.size()]));
String [] downRows = {"0","2","3"}; //下拉的列序号数组(序号从0开始)
try {
FileHelper.createExcelTemplate(fileName, handers, downData, downRows, response);
} catch (Exception e) {
CommonResponseUtil.failure(e.getMessage());
}
return CommonResponseUtil.success();
}
/**
* 导入
*
* @return
*/
@TycloudOperation(ApiLevel = UserType.AGENCY)
@PostMapping(value = "/import")
@ApiOperation(httpMethod = "POST", value = "模板填充数据导入", notes = "模板填充数据导入")
public ResponseModel importFaultCase(@ApiParam(value="导入数据文件", required=true) MultipartFile file) {
String fileName = file.getOriginalFilename();
if (!fileName.endsWith(".xls")) {
return CommonResponseUtil.failure("文件格式错误");
}
try {
List<FaultCaseImportParam> list = FileHelper.importExcel(file, 0, 1, FaultCaseImportParam.class);
if (0 < list.size()) {
List<FaultCase> cases = new ArrayList<>();
for (FaultCaseImportParam dto : list) {
FaultCase faultCase = new FaultCase();
BeanUtils.copyProperties(dto, faultCase);
if (StringUtil.isNotEmpty(dto.getSystemInfo())) {
String[] strings = dto.getSystemInfo().split("@");
faultCase.setSystemName(strings[0]);
faultCase.setSystemId(strings[1]);
faultCase.setSystemTypeCode(strings[2]);
} else {
return CommonResponseUtil.failure("请补充消防系统信息!");
}
if (StringUtil.isNotEmpty(dto.getFaultLevel())) {
String[] levels = dto.getFaultLevel().split("@");
faultCase.setFaultLevel(levels[1]);
} else {
return CommonResponseUtil.failure("请补充故障等级信息!");
}
if (StringUtil.isNotEmpty(dto.getEquipId())) {
EquipmentSpecific specific = equipmentSpecificService.getOne(new QueryWrapper<EquipmentSpecific>().eq("id", Long.valueOf(dto.getEquipId())));
if (ObjectUtils.isEmpty(specific)) {
return CommonResponseUtil.failure("部件信息有误!");
} else {
faultCase.setEquipId(dto.getEquipId());
faultCase.setEquipName(specific.getName());
}
List<EquiplistSpecificBySystemVO> equips = fireFightingSystemService.getEquiplistBySystemId(Long.valueOf(faultCase.getSystemId()));
if (0 == equips.size()) {
return CommonResponseUtil.failure("对应的消防系统下未找到导入的部件!");
}
} else {
return CommonResponseUtil.failure("请补充部件id!");
}
cases.add(faultCase);
}
faultCaseService.saveOrUpdateBatch(cases);
}
return CommonResponseUtil.success();
} catch (Exception e) {
e.printStackTrace();
return CommonResponseUtil.failure(e.getLocalizedMessage());
}
}
/**
* 统计导出
*
* @return
*/
@TycloudOperation(ApiLevel = UserType.AGENCY)
@ApiOperation(httpMethod = "GET",value = "统计列表", notes = "统计导出")
@GetMapping(value = "/system/list")
public ResponseModel<List<Map<String, Object>>> getFaultCaseList() {
return CommonResponseUtil.success(faultCaseService.getFaultCaseList());
}
/**
* 统计导出
*
* @return
*/
@TycloudOperation(ApiLevel = UserType.AGENCY)
@ApiOperation(httpMethod = "GET",value = "获取系统下装备列表", notes = "获取系统下装备列表")
@GetMapping(value = "/equip/list")
public ResponseModel<List<EquiplistSpecificBySystemVO>> getEquipListBySystemId(@RequestParam(value = "systemId") String systemId) {
return CommonResponseUtil.success(fireFightingSystemService.getEquipBySystemId(Long.valueOf(systemId)));
}
}
package com.yeejoin.equipmanage.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.equipmanage.common.entity.FaultCase;
import com.yeejoin.equipmanage.common.entity.vo.BuildingVideoListVO;
import com.yeejoin.equipmanage.common.entity.vo.BuildingVideoVO;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
/**
* 信号分类量测枚举表 Mapper 接口
*
* @author system_generator
* @date 2022-02-18
*/
public interface FaultCaseMapper extends BaseMapper<FaultCase> {
Page<FaultCase> listPage(@Param("page") Page page, @Param("dto") FaultCase dto);
List<Map<String, Object>> getFaultCaseList();
}
......@@ -25,6 +25,8 @@ public interface FireFightingSystemMapper extends BaseMapper<FireFightingSystemE
*/
List<EquiplistSpecificBySystemVO> getEquiplistBySystemId(Long systemId);
List<EquiplistSpecificBySystemVO> getEquipBySystemId(Long systemId);
/**
* 根据系统id查询设备列表
*
......
package com.yeejoin.equipmanage.service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.yeejoin.equipmanage.common.entity.FaultCase;
import com.yeejoin.equipmanage.common.entity.vo.BuildingVideoListVO;
import com.yeejoin.equipmanage.common.entity.vo.BuildingVideoVO;
import java.util.List;
import java.util.Map;
/**
* 信号分类量测枚举表接口类
*
* @author system_generator
* @date 2022-02-18
*/
public interface IFaultCaseService extends IService<FaultCase> {
Page<FaultCase> listPage(Page page, FaultCase faultCase);
List<Map<String, Object>> getFaultCaseList();
}
......@@ -26,6 +26,8 @@ public interface IFireFightingSystemService extends IService<FireFightingSystemE
*/
List<EquiplistSpecificBySystemVO> getEquiplistBySystemId(Long systemId);
List<EquiplistSpecificBySystemVO> getEquipBySystemId(Long systemId);
/**
* 根据系统id查询设备列表
*
......
......@@ -4,6 +4,8 @@ package com.yeejoin.equipmanage.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.yeejoin.equipmanage.common.entity.SignalClassify;
import java.util.List;
/**
* 信号分类量测枚举表接口类
*
......@@ -13,4 +15,6 @@ import com.yeejoin.equipmanage.common.entity.SignalClassify;
public interface ISignalClassifyService extends IService<SignalClassify> {
SignalClassify getTypeNameByCode(String code);
List<SignalClassify> getList();
}
package com.yeejoin.equipmanage.service.impl;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yeejoin.equipmanage.common.entity.FaultCase;
import com.yeejoin.equipmanage.common.enums.EmergencyLevelEum;
import com.yeejoin.equipmanage.mapper.FaultCaseMapper;
import com.yeejoin.equipmanage.service.IFaultCaseService;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* 信号分类量测枚举表服务实现类
*
* @author system_generator
* @date 2022-02-18
*/
@Service
public class FaultCaseServiceImpl extends ServiceImpl<FaultCaseMapper, FaultCase> implements IFaultCaseService {
@Override
public Page<FaultCase> listPage(Page page, FaultCase faultCase) {
Page<FaultCase> pages = this.baseMapper.listPage(page, faultCase);
if (0 < pages.getRecords().size()) {
pages.getRecords().stream().map(x -> x.setFaultLevel(EmergencyLevelEum.getNameByCode(x.getFaultLevel()))).collect(Collectors.toList());
}
return pages;
}
@Override
public List<Map<String, Object>> getFaultCaseList() {
return this.baseMapper.getFaultCaseList();
}
}
\ No newline at end of file
......@@ -182,6 +182,11 @@ public class FireFightingSystemServiceImpl extends ServiceImpl<FireFightingSyste
getEquiplistBySystemId(Long systemId) {
return this.baseMapper.getEquiplistBySystemId(systemId);
}
@Override
public List<EquiplistSpecificBySystemVO> getEquipBySystemId(Long systemId) {
return this.baseMapper.getEquipBySystemId(systemId);
}
@Override
public IPage<EquiplistSpecificBySystemVO> getEquiplistBySystemIdPage(Long systemId, int size, int current) {
IPage<EquiplistSpecificBySystemVO> page = new Page();
......
......@@ -7,6 +7,8 @@ import com.yeejoin.equipmanage.mapper.SignalClassifyMapper;
import com.yeejoin.equipmanage.service.ISignalClassifyService;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* 信号分类量测枚举表服务实现类
*
......@@ -20,4 +22,9 @@ public class SignalClassifyServiceImpl extends ServiceImpl<SignalClassifyMapper,
public SignalClassify getTypeNameByCode(String code) {
return this.baseMapper.selectOne(new LambdaQueryWrapper<SignalClassify>().eq(SignalClassify::getTypeCode, code));
}
@Override
public List<SignalClassify> getList() {
return this.baseMapper.selectList(new LambdaQueryWrapper<>());
}
}
\ No newline at end of file
package com.yeejoin.equipmanage.utils;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import org.apache.commons.io.FileUtils;
import org.apache.poi.hslf.usermodel.HSLFSlideShow;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.ByteBuffer;
import java.nio.channels.Channel;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
*
* 类描述: 包括功能、用途、现存BUG,以及其它别人可能感兴趣的介绍。
*
* @see 需要参见的其它类(可选)
* @version 1.0
* @date 2016年7月27日
* @author <a href="mailto:Ydm@nationsky.com">Ydm</a>
* @since JDK 1.7
*/
public class FileHelper {
private static final Logger log = LoggerFactory.getLogger(FileHelper.class);
/**
*
* @param file
* @return
*/
public static boolean isWord2003(File file) {
try (InputStream is = new FileInputStream(file);
HWPFDocument hwpfDocument = new HWPFDocument(is);) {
} catch (Exception e) {
return false;
}
return true;
}
public static boolean isWord2007(File file) {
InputStream is = null;
try {
is = new FileInputStream(file);
new XWPFDocument(is).close();
} catch (Exception e) {
return false;
} finally {
try {
if (null != is) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return true;
}
/**
*
* @param file
* @return
*/
public static boolean isPPT2003(File file) {
try ( InputStream is = new FileInputStream(file);
HSLFSlideShow ppt = new HSLFSlideShow(is);) {
} catch (Exception e) {
return false;
}
return true;
}
/**
*
* @param path
* @return
*/
public static StringBuffer readFile(String path) {
StringBuffer buffer = new StringBuffer();
File file = new File(path);
if (file.exists()) {
try (InputStream is = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(is))) {
String content = br.readLine();
while (null != content) {
buffer.append(content);
content = br.readLine();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return buffer;
}
/**
* 读取文件,并按照指定的分割符保存文件
* @param path 文件的路径
* @param split 分割内容的标识
* @return 按照传入的分割符,标识的字符串
*/
public static StringBuffer readFile(String path, String split) {
StringBuffer buffer = new StringBuffer();
File file = new File(path);
if (file.exists()) {
try (InputStream is = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(is))) {
String content = br.readLine();
while (null != content) {
buffer.append(content).append(split);
content = br.readLine();
}
} catch (Exception exception) {
exception.printStackTrace();
}
}
return buffer;
}
/**
* 将传入的字符串写入到指定的路径的文件下
* @param content 将要写入文件的内容
* @param path 写入内容的文件路径
*/
public static void writeFile(String content, String path) {
File file = new File(path);
try (OutputStream fos = new FileOutputStream(file);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos, StandardCharsets.UTF_8))) {
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
bw.write(content);
} catch (IOException fnfe) {
fnfe.printStackTrace();
}
}
/**
* 将图片写成html文件
* @param size 图片数量
* @param path 保存html文件全路径
* @param fileName 图片路径
*/
public static void writeHtmlFile(int size, String path, String fileName) {
StringBuffer buffer = new StringBuffer();
buffer.append("<!DOCTYPE html><html><head>");
buffer.append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>");
buffer.append("<meta name=\"viewport\" ");
buffer.append("content=\"width=device-width,minimum-scale=1,maximum-scale=1,user-scalable=no,minimal-ui\"/>");
buffer.append("<meta name=\"format-detection\" content=\"telephone=no\"/>");
buffer.append("<meta http-equiv=\"Access-Control-Allow-Origin\" content=\"*\"/>");
buffer.append("<title>touch</title>");
buffer.append("<meta name=\"keywords\" content=\"\"/>");
buffer.append("<meta name=\"description\" content=\"\"/>");
buffer.append(
"<style type=\"text/css\">body{width:100%;height:auto;position:relative;}img{max-width:100%;height:auto;margin:0 auto;}</style>");
buffer.append("</head>");
buffer.append("<body>");
for (int offset = 0; offset < size; offset++) {
buffer.append("<img src=\"" + fileName + "/" + (offset + 1) + ".png\" />");
buffer.append("<br />");
}
buffer.append("</body></html>");
// System.out.println(buffer.toString());
writeFile(buffer.toString(), path + ".html");
}
public static void writeHtmlFile(String path, String fileName) {
StringBuffer buffer = new StringBuffer();
buffer.append("<!DOCTYPE html><html><head>");
buffer.append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>");
buffer.append(
"<meta name=\"viewport\" content=\"width=device-width,minimum-scale=1,maximum-scale=1,user-scalable=no,minimal-ui\"/>");
buffer.append("<meta name=\"format-detection\" content=\"telephone=no\"/>");
buffer.append("<meta http-equiv=\"Access-Control-Allow-Origin\" content=\"*\"/>");
buffer.append("<title>touch</title>");
buffer.append("<meta name=\"keywords\" content=\"\"/>");
buffer.append("<meta name=\"description\" content=\"\"/>");
buffer.append(
"<style type=\"text/css\">body{width:100%;height:auto;position:relative;}img{max-width:100%;height:auto;margin:0 auto;}</style>");
buffer.append("</head>");
buffer.append("<body>");
buffer.append("<img src=\"" + fileName + "/" + fileName + ".png\" />");
buffer.append("<br />");
buffer.append("</body></html>");
// System.out.println(buffer.toString());
writeFile(buffer.toString(), path + ".html");
}
public static void write2Html(StringBuffer content, String path) {
StringBuffer buffer = new StringBuffer();
buffer.append(
"<html><head><meta http-equiv=\"Access-Control-Allow-Origin\" content=\"*\"></head><body><div align=\"left\">");
buffer.append("<p>" + content + "</p>");
buffer.append("</div></body></html>");
// System.out.println(buffer.toString());
writeFile(buffer.toString(), path + ".html");
}
public static void mkdirFiles(String filePath, String fileType) {
File file = new File(filePath + "/" + fileType);
if (!file.exists()) {
file.mkdirs();
}
}
/**
* 删除文件空行
*
* @param
* @param outPutFile
* @throws IOException
*/
public static void rmrBlankLines(String inputFile, String outPutFile) throws IOException {
File htmFile = new File(inputFile);
// 以GB2312读取文件
try (BufferedReader br = new BufferedReader(new FileReader(htmFile));
BufferedWriter bw = new BufferedWriter(new FileWriter(new File(outPutFile)));) {
String result = null;
while (null != (result = br.readLine())) {
if (!"".equals(result.trim())) {
bw.write(result + "\r\n");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @param htmFilePath
* @throws IOException
*/
public static void parseH2(String htmFilePath) throws IOException {
File htmFile = new File(htmFilePath);
Document doc = Jsoup.parse(htmFile, "UTF-8");
doc.getElementsByAttribute("h2");
Elements content = doc.getElementsByTag("h2");
for (Element meta : content) {
meta.attr("style", "text-align:center");
}
FileUtils.writeStringToFile(htmFile, doc.html(), "UTF-8");
}
/**
* @param htmFilePath
* @throws IOException
*/
public static void parseCharset(String htmFilePath) throws IOException {
File htmFile = new File(htmFilePath);
// 以GB2312读取文件
Document doc = Jsoup.parse(htmFile, "utf-8");
// 获取html节点
Elements content = doc.getElementsByAttributeValueStarting("content", "text/html;");
Elements brs = doc.getElementsByTag("<br>");
for (Element br : brs) {
br.before("<br />");
br.remove();
}
for (Element meta : content) {
// 获取content节点,修改charset属性
meta.attr("content", "text/html; charset=utf-8");
break;
}
// 转换成utf-8编码的文件写入
System.out.println(doc.html());
FileUtils.writeStringToFile(htmFile, doc.html(), "utf-8");
}
/**
* @param htmFilePath
* @throws IOException
*/
public static void parse(String htmFilePath) throws IOException {
File htmFile = new File(htmFilePath);
// 以GB2312读取文件
Document doc = Jsoup.parse(htmFile, "utf-8");
String xmlns = doc.getElementsByTag("html").attr("xmlns");
if (null == xmlns || "".equals(xmlns)) {
return;
}
doc.getElementsByTag("html").removeAttr("xmlns");
Element head = doc.head();
/*
* Elements headChildren = head.children(); for(Element children : headChildren) { Elements
* metas = children.getElementsByTag("meta"); for(Element meta : metas) { meta.remove(); } }
*/
head.appendElement("meta").attr("name", "viewport").attr("content",
"width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no");
// 获取html节点
Element element = doc.body();
Elements content = head.getElementsByAttributeValueStarting("name", "meta:page-count");
for (Element meta : content) {
String value = meta.attr("content");
try {
Integer count = Integer.valueOf(value);
Elements ps = element.getElementsByTag("p");
Iterator<Element> iterator = ps.iterator();
while (iterator.hasNext()) {
Element p = iterator.next();
String text = p.text();
if (text.equals("- " + count + " -")) {
for (int offset = count; offset > 0; offset--) {
p.remove();
p = iterator.next();
text = p.text();
}
}
if (text.equals("")) {
p.remove();
p = iterator.next();
}
p.attr("align", "center");
p.attr("style", "font-size:1.5rem;");
break;
}
} catch (Exception e) {
}
// 获取content节点,修改charset属性
// meta.attr("content", "text/html; charset=utf-8");
break;
}
// 转换成utf-8编码的文件写入
FileUtils.writeStringToFile(htmFile, "<!DOCTYPE html>" + doc.html(), "utf-8");
}
public static void checkHtmlEndTag(String htmFilePath) throws IOException {
File htmFile = new File(htmFilePath);
// 以GB2312读取文件
Document doc = Jsoup.parse(htmFile, "utf-8");
Elements all = doc.getElementsByTag("html");
for (Element element : all) {
parseElements(all, element);
}
FileUtils.writeStringToFile(htmFile, doc.html(), "utf-8");
}
public static void parseElements(Elements elements, Element element) {
int childNodeSize = elements.size();
if (0 < childNodeSize) {
for (int offset = 0; offset < childNodeSize; offset++) {
parseElements(elements.get(offset).children(), elements.get(offset));
}
} else {
String tagName = element.tagName();
String content = element.toString();
if (tagName.length() + 3 > content.length()) {
element.text("");
} else {
try {
String endTag =
content.substring(content.length() - tagName.length() - 3, content.length());
if (!("</" + tagName + ">").equals(endTag)) {
element.text("");
}
} catch (Exception w) {}
}
}
}
public static void changeImageType(String htmFilePath) throws IOException {
File htmFile = new File(htmFilePath);
// 以GB2312读取文件
Document doc = Jsoup.parse(htmFile, "utf-8");
Elements elements = doc.getElementsByTag("img");
String imgPath = "";
for (Element element : elements) {
String src = element.attr("src");
String[] sp = src.split("\\.");
String newSrc = htmFile.getParent() + File.separator + sp[0] + ".jpg";
imgPath = src;
element.attr("src", newSrc);
}
FileUtils.writeStringToFile(htmFile, doc.html(), "utf-8");
String name = htmFile.getName();
htmFilePath = htmFilePath.substring(0, htmFilePath.length() - name.length()) + imgPath;
File file = new File(htmFilePath);
File[] files = file.getParentFile().listFiles();
for (File file2 : files) {
String filePath = file2.getPath();
String[] sp = filePath.split("\\.");
String newSrc = sp[0] + ".jpg";
FileHelper.copyFile(filePath, newSrc, true);
}
}
public static void nioTransferCopy(File source, File target) {
FileChannel in = null;
FileChannel out = null;
FileInputStream inStream = null;
FileOutputStream outStream = null;
try {
inStream = new FileInputStream(source);
outStream = new FileOutputStream(target);
in = inStream.getChannel();
out = outStream.getChannel();
in.transferTo(0, in.size(), out);
} catch (IOException e) {
e.printStackTrace();
} finally {
close(inStream);
close(in);
close(outStream);
close(out);
}
}
private static boolean nioBufferCopy(File source, File target) {
FileChannel in = null;
FileChannel out = null;
FileInputStream inStream = null;
FileOutputStream outStream = null;
try {
inStream = new FileInputStream(source);
outStream = new FileOutputStream(target);
in = inStream.getChannel();
out = outStream.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(4096);
while (in.read(buffer) != -1) {
buffer.flip();
out.write(buffer);
buffer.clear();
}
} catch (IOException e) {
e.printStackTrace();
return false;
} finally {
close(inStream);
close(in);
close(outStream);
close(out);
}
return true;
}
public static void customBufferStreamCopy(File source, File target) {
InputStream fis = null;
OutputStream fos = null;
try {
fis = new FileInputStream(source);
fos = new FileOutputStream(target);
byte[] buf = new byte[4096];
int i;
while ((i = fis.read(buf)) != -1) {
fos.write(buf, 0, i);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
close(fis);
close(fos);
}
}
/**
* 复制单个文件
*
* @param srcFileName 待复制的文件名
* @param destFileName 目标文件名
* @param overlay 如果目标文件存在,是否覆盖
* @return 如果复制成功返回true,否则返回false
*/
public static boolean copyFile(String srcFileName, String destFileName, boolean overlay) {
File srcFile = new File(srcFileName);
// 判断源文件是否存在
if (!srcFile.exists()) {
log.info("input file not null");
return false;
} else if (!srcFile.isFile()) {
log.info("input file is not file");
return false;
}
// 判断目标文件是否存在
File destFile = new File(destFileName);
if (destFile.exists()) {
// 如果目标文件存在并允许覆盖
if (overlay) {
// 删除已经存在的目标文件,无论目标文件是目录还是单个文件
new File(destFileName).delete();
}
} else {
// 如果目标文件所在目录不存在,则创建目录
if (!destFile.getParentFile().exists()) {
// 目标文件所在目录不存在
if (!destFile.getParentFile().mkdirs()) {
// 复制文件失败:创建目标文件所在目录失败
return false;
}
}
}
boolean result = nioBufferCopy(srcFile, destFile);
return result;
}
/**
* 复制整个目录的内容
*
* @param srcDirName 待复制目录的目录名
* @param destDirName 目标目录名
* @param overlay 如果目标目录存在,是否覆盖
* @return 如果复制成功返回true,否则返回false
*/
public static boolean copyDirectory(String srcDirName, String destDirName, boolean overlay) {
// 判断源目录是否存在
File srcDir = new File(srcDirName);
if (!srcDir.exists()) {
log.info("srcDir not found");
return false;
} else if (!srcDir.isDirectory()) {
log.info("srcDir not Directory");
return false;
}
// 如果目标目录名不是以文件分隔符结尾,则加上文件分隔符
if (!destDirName.endsWith(File.separator)) {
destDirName = destDirName + File.separator;
}
File destDir = new File(destDirName);
// 如果目标文件夹存在
if (destDir.exists()) {
// 如果允许覆盖则删除已存在的目标目录
if (overlay) {
new File(destDirName).delete();
} else {
log.info("");
return false;
}
} else {
// 创建目的目录
System.out.println("目的目录不存在,准备创建。。。");
if (!destDir.mkdirs()) {
System.out.println("复制目录失败:创建目的目录失败!");
return false;
}
}
boolean flag = true;
File[] files = srcDir.listFiles();
for (int i = 0; i < files.length; i++) {
// 复制文件
if (files[i].isFile()) {
flag = FileHelper.copyFile(files[i].getAbsolutePath(), destDirName + files[i].getName(),
overlay);
if (!flag) {
break;
}
} else if (files[i].isDirectory()) {
flag = FileHelper.copyDirectory(files[i].getAbsolutePath(),
destDirName + files[i].getName(), overlay);
if (!flag) {
break;
}
}
}
if (!flag) {
log.info("copy Directory fail");
return false;
} else {
return true;
}
}
/**
* 关闭资源
* @param object 需要关闭的对象
*/
public static void close(Object object) {
if (null == object) {
return;
}
try {
if (object instanceof InputStream) {
((InputStream) object).close();
} else if (object instanceof OutputStream) {
((OutputStream) object).close();
} else if (object instanceof Channel) {
((Channel) object).close();
}
} catch (Exception exce) {
System.err.println(exce.getMessage());
}
}
/**
* 合并excel表格的sheet
*
* @param htmFilePath html文件路径
* @throws IOException 打开文件异常
*/
public static void mergeTable(String htmFilePath) throws IOException {
File htmFile = new File(htmFilePath);
// 以GB2312读取文件
Document doc = Jsoup.parse(htmFile, "utf-8");
Integer tableMaxSize = getMaxTableSize(doc);
Elements allTable = doc.getElementsByTag("tbody");
Element max = null;
for (Element table : allTable) {
Elements elements = table.children();
if (0 >= elements.size()) {
table.parent().remove();
continue;
}
int size = elements.first().children().size();
if (size >= tableMaxSize) {
max = table;
continue;
}
for (Element tr : elements) {
Elements td = tr.children();
for (int offset = tableMaxSize; offset > td.size(); offset--) {
Element tdd = doc.createElement("td");
tr.appendChild(tdd);
}
max.appendChild(tr);
}
table.parent().remove();
}
FileUtils.writeStringToFile(htmFile, doc.html(), "utf-8");
}
private static Integer getMaxTableSize(Document doc) {
Elements allTable = doc.getElementsByTag("tbody");
TreeSet<Integer> tableSize = new TreeSet<Integer>();
for (Element table : allTable) {
Elements elements = table.children();
int size = 0;
try {
size = elements.first().children().size();
} catch (Exception e) {
size = -1;
}
if (tableSize.contains(size)) {
size--;
}
tableSize.add(size);
}
return tableSize.last();
}
/**
* 获取文件css样式
* @param src 文件
* @return 文件css样式
* @throws IOException 打开文件异常
*/
public static final StringBuffer getHtmlCss(String src) throws IOException {
File htmFile = new File(src);
// 以GB2312读取文件
Document doc = Jsoup.parse(htmFile, "utf-8");
Elements styles = doc.getElementsByTag("style");
StringBuffer csStringBuffer = new StringBuffer();
for (Element style : styles) {
csStringBuffer.append(style.toString().replace("<style>", "").replace("</style>", ""));
}
Elements links = doc.getElementsByTag("link");
for (Element style : links) {
String href = style.attr("href");
String realPath = src + File.separator + href;
StringBuffer link = FileHelper.readFile(realPath);
csStringBuffer.append(link);
}
return csStringBuffer;
}
public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass,String fileName,boolean isCreateHeader, HttpServletResponse response){
ExportParams exportParams = new ExportParams(title, sheetName);
exportParams.setCreateHeadRows(isCreateHeader);
defaultExport(list, pojoClass, fileName, response, exportParams);
}
public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass,String fileName, HttpServletResponse response){
defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName));
}
public static void exportExcel(List<Map<String, Object>> list, String fileName, HttpServletResponse response){
defaultExport(list, fileName, response);
}
private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response, ExportParams exportParams) {
Workbook workbook = ExcelExportUtil.exportExcel(exportParams,pojoClass,list);
if (workbook != null);
downLoadExcel(fileName, response, workbook);
}
private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) {
try {
// String name = new String(fileName.getBytes("UTF-8"), "ISO8859_1");
// response.setHeader("content-Type", "application/vnd.ms-excel");
// response.setHeader("Content-Disposition",
// "attachment;filename=" + name);
response.setCharacterEncoding("UTF-8");
response.setHeader("content-Type", "application/vnd.ms-excel");
response.setHeader("Content-Disposition",
"attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
workbook.write(response.getOutputStream());
} catch (IOException e) {
throw new RuntimeException(e.getMessage());
}
}
private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) {
Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);
if (workbook != null);
downLoadExcel(fileName, response, workbook);
}
public static <T> List<T> importExcel(String filePath,Integer titleRows,Integer headerRows, Class<T> pojoClass){
if (ObjectUtils.isEmpty(filePath)){
return null;
}
ImportParams params = new ImportParams();
params.setTitleRows(titleRows);
params.setHeadRows(headerRows);
List<T> list = null;
try {
list = ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);
}catch (NoSuchElementException e){
throw new RuntimeException("模板不能为空");
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}
return list;
}
public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass){
if (file == null){
return null;
}
ImportParams params = new ImportParams();
params.setTitleRows(titleRows);
params.setHeadRows(headerRows);
List<T> list = null;
try {
list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);
}catch (NoSuchElementException e){
throw new RuntimeException("excel文件不能为空");
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}
return list;
}
public static void exportZip(List<Map<String, Object>> list, String fileName, HttpServletResponse response) {
try {
response.setContentType("multipart/form-data");
response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("下载文件名编码时出现错误.");
}
OutputStream outputStream = null;
ZipOutputStream zos = null;
try {
outputStream = response.getOutputStream();
zos = new ZipOutputStream(outputStream);
downloadZip(fileName.replace(".zip", ""), zos, list);
} catch (IOException e) {
throw new RuntimeException("下载文件名编码时出现错误.");
} finally {
if(zos != null) {
try {
zos.close();
} catch (Exception e2) {
throw new RuntimeException("下载文件名编码时出现错误.");
}
}
if(outputStream != null) {
try {
outputStream.close();
} catch (Exception e2) {
throw new RuntimeException("下载文件名编码时出现错误.");
}
}
}
}
public static void downloadZip(String baseDir, ZipOutputStream zos, List<Map<String, Object>> list) {
for (Map<String, Object> map : list) {
String checkId = map.get("id").toString();
//文件名称(带后缀)
String fileName = map.get("photoData").toString();
InputStream is = null;
BufferedInputStream in = null;
byte[] buffer = new byte[1024];
int len;
//创建zip实体(一个文件对应一个ZipEntry)
ZipEntry entry = new ZipEntry(baseDir + fileName.substring(fileName.lastIndexOf('/'), fileName.length()));
try {
//获取需要下载的文件流
URL url = new URL(fileName);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//下载
is = conn.getInputStream();
// File file = new File(fileName);
// is = new FileInputStream(file);
in = new BufferedInputStream(is);
zos.putNextEntry(entry);
//文件流循环写入ZipOutputStream
while ((len = in.read(buffer)) != -1 ) {
zos.write(buffer, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if(entry != null) {
try {
zos.closeEntry();
} catch (Exception e2) {
}
}
if(in != null) {
try {
in.close();
} catch (Exception e2) {
}
}
if(is != null) {
try {
is.close();
}catch (Exception e) {
}
}
}
}
}
/**
* @Title: createExcelTemplate
* @Description: 生成Excel导入模板
* @param @param filePath Excel文件路径
* @param @param handers Excel列标题(数组)
* @param @param downData 下拉框数据(数组)
* @param @param downRows 下拉列的序号(数组,序号从0开始)
* @return void
* @throws
*/
public static void createExcelTemplate(String fileName, String[] handers,
List<String[]> downData, String[] downRows, HttpServletResponse response){
HSSFWorkbook wb = new HSSFWorkbook();//创建工作薄
//表头样式
HSSFCellStyle style = wb.createCellStyle();
style.setAlignment(HorizontalAlignment.CENTER); // 创建一个居中格式
//字体样式
HSSFFont fontStyle = wb.createFont();
fontStyle.setFontName("微软雅黑");
fontStyle.setFontHeightInPoints((short)12);
fontStyle.setBold(true);
style.setFont(fontStyle);
//新建sheet
HSSFSheet sheet1 = wb.createSheet("Sheet1");
HSSFSheet sheet2 = wb.createSheet("Sheet2");
HSSFSheet sheet3 = wb.createSheet("Sheet3");
//生成sheet1内容
HSSFRow rowFirst = sheet1.createRow(0);//第一个sheet的第一行为标题
//写标题
for(int i=0;i<handers.length;i++){
HSSFCell cell = rowFirst.createCell(i); //获取第一行的每个单元格
sheet1.setColumnWidth(i, 4000); //设置每列的列宽
cell.setCellStyle(style); //加样式
cell.setCellValue(handers[i]); //往单元格里写数据
}
//设置下拉框数据
String[] arr = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
int index = 0;
HSSFRow row = null;
for(int r=0;r<downRows.length;r++){
String[] dlData = downData.get(r);//获取下拉对象
int rownum = Integer.parseInt(downRows[r]);
if(dlData==null){
continue;
}
if(dlData.length<5){ //255以内的下拉
//255以内的下拉,参数分别是:作用的sheet、下拉内容数组、起始行、终止行、起始列、终止列
sheet1.addValidationData(setDataValidation(sheet1, dlData, 1, dlData.length, rownum ,rownum)); //超过255个报错
} else { //255以上的下拉,即下拉列表元素很多的情况
//1、设置有效性
//String strFormula = "Sheet2!$A$1:$A$5000" ; //Sheet2第A1到A5000作为下拉列表来源数据
String strFormula = "Sheet2!$"+arr[index]+"$1:$"+arr[index]+"$"+dlData.length; //Sheet2第A1到A5000作为下拉列表来源数据
sheet2.setColumnWidth(r, 4000); //设置每列的列宽
//设置数据有效性加载在哪个单元格上,参数分别是:从sheet2获取A1到A5000作为一个下拉的数据、起始行、终止行、起始列、终止列
sheet1.addValidationData(SetDataValidation(strFormula, 1, dlData.length, rownum, rownum)); //下拉列表元素很多的情况
//2、生成sheet2内容
for(int j=0;j<dlData.length;j++){
if(index==0){ //第1个下拉选项,直接创建行、列
row = sheet2.createRow(j); //创建数据行
sheet2.setColumnWidth(j, 4000); //设置每列的列宽
row.createCell(0).setCellValue(dlData[j]); //设置对应单元格的值
} else { //非第1个下拉选项
int rowCount = sheet2.getLastRowNum();
//System.out.println("========== LastRowNum =========" + rowCount);
if(j<=rowCount){ //前面创建过的行,直接获取行,创建列
//获取行,创建列
sheet2.getRow(j).createCell(index).setCellValue(dlData[j]); //设置对应单元格的值
} else { //未创建过的行,直接创建行、创建列
sheet2.setColumnWidth(j, 4000); //设置每列的列宽
//创建行、创建列
sheet2.createRow(j).createCell(index).setCellValue(dlData[j]); //设置对应单元格的值
}
}
}
index++;
}
}
downLoadExcel(fileName, response, wb);
}
/**
*
* @Title: SetDataValidation
* @Description: 下拉列表元素很多的情况 (255以上的下拉)
* @param @param strFormula
* @param @param firstRow 起始行
* @param @param endRow 终止行
* @param @param firstCol 起始列
* @param @param endCol 终止列
* @param @return
* @return HSSFDataValidation
* @throws
*/
private static HSSFDataValidation SetDataValidation(String strFormula,
int firstRow, int endRow, int firstCol, int endCol) {
// 设置数据有效性加载在哪个单元格上。四个参数分别是:起始行、终止行、起始列、终止列
CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
DVConstraint constraint = DVConstraint.createFormulaListConstraint(strFormula);
HSSFDataValidation dataValidation = new HSSFDataValidation(regions,constraint);
dataValidation.createErrorBox("Error", "Error");
dataValidation.createPromptBox("", null);
return dataValidation;
}
/**
*
* @Title: setDataValidation
* @Description: 下拉列表元素不多的情况(255以内的下拉)
* @param @param sheet
* @param @param textList
* @param @param firstRow
* @param @param endRow
* @param @param firstCol
* @param @param endCol
* @param @return
* @return DataValidation
* @throws
*/
private static DataValidation setDataValidation(Sheet sheet, String[] textList, int firstRow, int endRow, int firstCol, int endCol) {
DataValidationHelper helper = sheet.getDataValidationHelper();
//加载下拉列表内容
DataValidationConstraint constraint = helper.createExplicitListConstraint(textList);
//DVConstraint constraint = new DVConstraint();
constraint.setExplicitListValues(textList);
//设置数据有效性加载在哪个单元格上。四个参数分别是:起始行、终止行、起始列、终止列
CellRangeAddressList regions = new CellRangeAddressList((short) firstRow, (short) endRow, (short) firstCol, (short) endCol);
//数据有效性对象
DataValidation data_validation = helper.createValidation(constraint, regions);
//DataValidation data_validation = new DataValidation(regions, constraint);
return data_validation;
}
/**
* @Title: getExcel
* @Description: 下载指定路径的Excel文件
* @param @param url 文件路径
* @param @param fileName 文件名
* @param @param response
* @return void
* @throws
*/
public static void getExcel(String url, String fileName, HttpServletResponse response,HttpServletRequest request){
//通过文件路径获得File对象
File file = new File(url);
//1.设置文件ContentType类型,这样设置,会自动判断下载文件类型
response.setContentType("multipart/form-data");
//2.设置文件头:最后一个参数是设置下载文件名
try {
response.setHeader("Content-disposition", "attachment; filename=\""
+ encodeChineseDownloadFileName(request, fileName+".xls") +"\"");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try ( FileInputStream in = new FileInputStream(file);
OutputStream out = new BufferedOutputStream(response.getOutputStream());) {
// response.setHeader("Content-Disposition", "attachment;filename="
// + new String(fileName.getBytes("UTF-8"), "ISO-8859-1") + ".xls"); //中文文件名
//3.通过response获取OutputStream对象(out)
int b = 0;
byte[] buffer = new byte[2048];
while ((b=in.read(buffer)) != -1){
out.write(buffer,0,b); //4.写到输出流(out)中
}
out.flush();
} catch (IOException e) {
log.error("下载Excel模板异常", e);
}
}
/**
*
* @Title: encodeChineseDownloadFileName
* @Description: TODO(这里用一句话描述这个方法的作用)
* @param @param request
* @param @param pFileName
* @param @return
* @param @throws UnsupportedEncodingException
* @return String
* @throws
*/
private static String encodeChineseDownloadFileName(HttpServletRequest request, String pFileName)
throws UnsupportedEncodingException {
String filename = null;
String agent = request.getHeader("USER-AGENT");
//System.out.println("agent==========》"+agent);
if (null != agent) {
if (-1 != agent.indexOf("Firefox")) {//Firefox
filename = "=?UTF-8?B?" + (new String(org.apache.commons.codec.binary.Base64.encodeBase64(pFileName.getBytes("UTF-8")))) + "?=";
} else if (-1 != agent.indexOf("Chrome")) {//Chrome
filename = new String(pFileName.getBytes(), "ISO8859-1");
} else {//IE7+
filename = URLEncoder.encode(pFileName, "UTF-8");
filename = StringUtils.replace(filename, "+", "%20");//替换空格
}
} else {
filename = pFileName;
}
return filename;
}
/**
* @Title: delFile
* @Description: 删除文件
* @param @param filePath 文件路径
* @return void
* @throws
*/
public static void delFile(String filePath) {
File delFile = new File(filePath);
delFile.delete();
}
}
package com.yeejoin.amos.boot.module.jcs.biz.controller;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.utils.DateUtils;
import com.yeejoin.amos.boot.biz.common.utils.RedisKey;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.module.common.api.core.framework.PersonIdentify;
import com.yeejoin.amos.boot.module.common.api.dto.FormValue;
import com.yeejoin.amos.boot.module.common.api.dto.OrgPersonFormDto;
......@@ -17,11 +21,13 @@ import org.springframework.web.bind.annotation.RestController;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import com.yeejoin.amos.boot.module.jcs.biz.service.impl.SignServiceImpl;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;
import org.springframework.beans.factory.annotation.Autowired;
......@@ -48,6 +54,10 @@ public class SignController extends BaseController {
@Autowired
OrgUsrServiceImpl iOrgUsrService;
@Autowired
RedisUtils redisUtils;
/**
* 新增打卡记录
*
......@@ -175,6 +185,29 @@ public class SignController extends BaseController {
}
/**
* 列表分页查询
*
* @return
*/
@TycloudOperation(ApiLevel = UserType.AGENCY)
@PostMapping(value = "/center/static/page")
@ApiOperation(httpMethod = "POST",value = "中心级卡片驻站消防员出勤柱状图", notes = "中心级卡片驻站消防员出勤柱状图")
public ResponseModel<Map<String, Object>> queryPeopleInfoForPage(@RequestBody SinStaticDto dto) {
ReginParams reginParam = JSON.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
String bizOrgCode = null;
if(null != reginParam) {
bizOrgCode = reginParam.getPersonIdentity().getBizOrgCode();
}
dto.setBizOrgCode(bizOrgCode);
List<Map<String, Object>> res = signServiceImpl.queryPeopleInfo(dto);
Map<String, Object> map1 = new HashMap<>();
map1.put("bizOrgCode", bizOrgCode);
map1.put("xData", res.stream().map(x -> x.get("date")).collect(Collectors.toList()));
map1.put("yData", res.stream().map(x -> x.get("signNum")).collect(Collectors.toList()));
return ResponseHelper.buildResponse(map1);
}
/**
* 列表全部数据查询
*
* @return
......
......@@ -81,6 +81,11 @@ public class SignServiceImpl extends BaseService<SignDto,Sign,SignMapper> implem
return sinStaticDtoIPage;
}
public List<Map<String, Object>> queryPeopleInfo(SinStaticDto dto) {
List<Map<String, Object>> res = this.baseMapper.queryPeopleInfo(dto);
return res;
}
/**
* 列表查询 示例
*/
......
......@@ -1095,4 +1095,18 @@ public class PlanTaskController extends AbstractBaseController {
}
}
@TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
@ApiOperation(value = "idx消防巡查报表调用", notes = "idx消防巡查报表调用")
@RequestMapping(value = "/task/info", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
public ResponseModel getPlanTaskInfo(@ApiParam(value = "站编码") @RequestParam(required = false) String bizOrgCode,
@ApiParam(value = "开始日期") @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date startDate,
@ApiParam(value = "结束日期") @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate) {
try {
Map<String, Object> map = planTaskService.queryPatrolInfo(bizOrgCode, startDate, endDate);
return CommonPatrolResponseUtil.success(map);
} catch (Exception e) {
log.error(e.getMessage(), e);
return CommonPatrolResponseUtil.failure("远程查询巡检信息失败!");
}
}
}
......@@ -224,4 +224,6 @@ public interface PlanTaskMapper extends BaseMapper {
Map<String, Object> queryPatrolInfoList(@Param(value="bizOrgCode") String bizOrgCode, @Param(value="startDate") Date startDate, @Param(value="endDate") Date endDate);
Map<String, Object> queryPatrolEquipInfo(@Param(value="bizOrgCode") String bizOrgCode, @Param(value="startDate") Date startDate, @Param(value="endDate") Date endDate);
List<Map<String, Object>> queryPatrolInfo(@Param(value="bizOrgCode") String bizOrgCode, @Param(value="startDate") Date startDate, @Param(value="endDate") Date endDate);
}
......@@ -2100,6 +2100,15 @@ public class PlanTaskServiceImpl implements IPlanTaskService {
return statics;
}
@Override
public Map<String, Object> queryPatrolInfo(String bizOrgCode, Date startDate, Date endDate) {
List<Map<String, Object>> list = new ArrayList<>();
list = planTaskMapper.queryPatrolInfo(bizOrgCode, startDate, endDate);
Map<String, Object> map = new HashMap<>();
map.put("patrol", list);
return map;
}
public static byte[] file2byte(File file) {
try {
FileInputStream in = new FileInputStream(file);
......
......@@ -200,4 +200,7 @@ public interface IPlanTaskService {
void download(HttpServletRequest request, HttpServletResponse response, String taskDetailId) throws UnsupportedEncodingException;
Map<String,Object> queryPatrolInfoList(String bizOrgCode, Date startDate, Date endDate);
Map<String,Object> queryPatrolInfo(String bizOrgCode, Date startDate, Date endDate);
}
......@@ -1000,6 +1000,7 @@
UPDATE wl_equipment_specific_index esi SET esi.type_code = ( SELECT type_code FROM wl_equipment_index wei WHERE esi.equipment_index_id = wei.id );
</sql>
</changeSet>
<changeSet author="keyong" id="1697017798">
<preConditions onFail="MARK_RAN">
<not>
......@@ -1011,4 +1012,32 @@
ALTER TABLE `f_fire_fighting_system` ADD COLUMN `system_run_state` VARCHAR (10) DEFAULT '1' COMMENT '站端消防系统运行状态 0-停止 1-运行';
</sql>
</changeSet>
<changeSet author="keyong" id="1698392137">
<preConditions onFail="MARK_RAN">
<not>
<tableExists tableName="wl_fault_case"/>
</not>
</preConditions>
<comment>create table wl_fault_case 故障案例</comment>
<sql>
CREATE TABLE `wl_fault_case` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键',
`system_id` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '系统id',
`system_type_code` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '系统名称',
`system_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '系统名称',
`equip_id` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '部件id',
`equip_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '部件名称',
`fault_level` varchar(20) DEFAULT NULL COMMENT '故障等级',
`fault_type` varchar(20) DEFAULT NULL COMMENT '故障类型',
`fault_describe` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '故障描述',
`handle_advise` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '处理建议',
`fault_effect` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '故障影响',
`preventive_measure` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '预防措施',
`create_date` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_date` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=20220218 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC COMMENT='故障案例表';
</sql>
</changeSet>
</databaseChangeLog>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.yeejoin.equipmanage.mapper.FaultCaseMapper">
<select id="listPage" resultType="com.yeejoin.equipmanage.common.entity.FaultCase">
SELECT
*
FROM
wl_fault_case
<where>
<if test="dto.systemId != null and dto.systemId != ''">
FIND_IN_SET(#{dto.systemId}, system_id)
</if>
<if test="dto.faultLevel != null and dto.faultLevel != ''">
AND fault_level = #{dto.faultLevel}
</if>
<if test="dto.faultType != null and dto.faultType != ''">
AND fault_type = #{dto.faultType}
</if>
<if test="dto.searchName != null and dto.searchName != ''">
AND (equip_name LIKE concat('%', #{dto.searchName},'%') OR system_name LIKE concat('%', #{dto.searchName},'%') OR fault_describe LIKE concat('%', #{dto.searchName},'%'))
</if>
</where>
</select>
<select id="getFaultCaseList" resultType="Map">
SELECT
count(1) AS `value`,
'' AS unit,
wfc.system_name AS `name`,
wfc.id AS `key`,
wfc.system_type_code AS typeCode
FROM
wl_fault_case wfc
GROUP BY wfc.system_type_code
</select>
</mapper>
......@@ -58,6 +58,16 @@
find_in_set(#{systemId},spe.system_id) and spe.single = true and wlsd.`status` = 1
</select>
<select id="getEquipBySystemId" resultMap="EquiplistBySystemId">
SELECT
spe.id,
spe.`name` equipment_name
FROM
wl_equipment_specific AS spe
WHERE
find_in_set(#{systemId},spe.system_id)
</select>
<select id="getEquiplistBySystemIdList" resultType="com.yeejoin.equipmanage.common.entity.vo.EquiplistSpecificBySystemVO">
SELECT
det.`name` equipmentName,
......
......@@ -1586,4 +1586,57 @@
</where>
) temp
</select>
<select id="queryPatrolInfo" resultType="Map">
SELECT
s1.date,
IFNULL(s2.`name`, '') AS `name`,
IFNULL(s2.`code`, '') AS `code`,
IFNULL(s2.`planPerson`, '') AS planPerson,
IFNULL(s2.`chargePerson`, '') AS chargePerson,
IFNULL(s2.`beginTime`, '') AS beginTime,
IFNULL(s2.`endTime`, '') AS endTime,
'patrol' AS type
FROM
(
SELECT
@s := @s + 1 AS `index`,
DATE_FORMAT( DATE_ADD(( DATE( DATE_ADD(#{endDate}, INTERVAL - DATEDIFF(#{endDate}, #{startDate}) DAY ))), INTERVAL @s DAY ), '%Y-%m-%d' ) AS date
FROM
mysql.help_topic,
( SELECT @s := -1 ) temp
WHERE
@s &lt; DATEDIFF(#{endDate}, #{startDate})
) s1
LEFT JOIN (
SELECT
s.*
FROM
(
SELECT
p.`name`,
pt.batch_no AS `code`,
pt.user_name AS planPerson,
pt.user_name AS chargePerson,
pt.begin_time AS beginTime,
pt.end_time AS endTime,
DATE_FORMAT(pt.check_date, '%Y-%m-%d') AS date
FROM
`p_plan_task` pt
LEFT JOIN p_plan p ON p.id = pt.plan_id
<where>
pt.finish_status=2
<if test="bizOrgCode != null">
AND p.biz_org_code LIKE CONCAT(#{bizOrgCode}, '%')
</if>
</where>
GROUP BY
LEFT (pt.check_date, 10)
ORDER BY
pt.check_date
) s
) s2 ON s2.date = s1.date
ORDER BY
s1.date
</select>
</mapper>
\ No newline at end of file
......@@ -311,12 +311,12 @@
<repository>
<id>Releases</id>
<name>Releases</name>
<url>http://36.46.149.14:8081/nexus/content/repositories/releases/</url>
<url>http://113.142.68.105:8081/nexus/content/repositories/releases/</url>
</repository>
<repository>
<id>Snapshots</id>
<name>Snapshots</name>
<url>http://36.46.149.14:8081/nexus/content/repositories/snapshots/</url>
<url>http://113.142.68.105:8081/nexus/content/repositories/snapshots/</url>
</repository>
<repository>
<id>com.e-iceblue</id>
......@@ -326,7 +326,7 @@
<repository>
<id>thirdparty</id>
<name>thirdparty</name>
<url>http://36.46.149.14:8081/nexus/content/repositories/thirdparty/</url>
<url>http://113.142.68.105:8081/nexus/content/repositories/thirdparty/</url>
</repository>
</repositories>
......
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