/**
* 移交数据包
* @param response
* @param dto
* @return
* @throws Exception
*/
public ResponseJson transferInfoPackage(HttpServletResponse response, ExportArchExcelDto dto) throws Exception {
// 基础路径
String basePath =transferPath + "/" + DateUtil.format(new Date(), "yyyyMMddhhmmss");
GdkItem gdkItem = gdkItemDao.findGdkItemById(dto.getGdkItemId());
/**
* 1、构造电子档案移交清单xlsx、目录文件xml、导入库条目xls、说明文件txt、档案元数据xml、档案原文
*/
electronicFileTransferList(dto, gdkItem, basePath);
/**
* 2、电子档案移交与接收登记表pdf
*/
electronicTransferRegister(gdkItem, basePath);
/**
* 3、打包
*/
String packageZipPath = ZipUtils.packageZip(basePath);
/**
* 4、更新移交记录
*/
gdkItem.setFileSource("1");
gdkItem.setZipInfo(packageZipPath);
gdkItem.setPassStatus("0");
gdkItemDao.updateGdkItem(gdkItem);
return new ResponseJson();
}
/**
* 电子档案移交清单、目录文件、电子档案移交与接收登记表
*
* @param dto
* @param gdkItem
* @param basePath
* @throws IOException
* @throws InvalidFormatException
*/
private void electronicFileTransferList(ExportArchExcelDto dto, GdkItem gdkItem, String basePath) throws IOException, InvalidFormatException {
//获取数据
List<Map> dataList = new ArrayList<>();
if (dto.getCheckData() != null && !dto.getCheckData().isEmpty()) {
dataList = dto.getCheckData();
} else {
Map<String, String> params = new HashMap<String, String>() {
{
this.put("count", "0");
}
};
try {
dto.getZyzkWjj().getPager().setPageSize(99999);
dataList = zyzkWjjService.searchByMultiCondition(params, dto.getZyzkWjj());
} catch (Throwable tw) {
tw.printStackTrace();
}
}
//map转实体类
List<ZlkWjj> zlkWjjList = new ArrayList<>();
for (int i = 0; i < dataList.size(); i++) {
ZlkWjj zlkWjj = BeanUtil.convertMapToBean(ZlkWjj.class, dataList.get(i));
zlkWjj.setPrintNumber(String.valueOf((i + 1)));
zlkWjjList.add(zlkWjj);
}
/**
* 1、电子档案移交清单
*/
//分割数据 每份12条
List<List<ZlkWjj>> assign = Lists.partition(zlkWjjList, 9999999);
//根据基础模板生成最终模板,使用POI进行excel读写
Workbook baseWorkbook = WorkbookFactory.create(new File(filePath + "/pdf/electronicFileTransferListTemplate.xls"));
//生成最终模板
Workbook dynamicWorkbook = ExcelCellCopy.dynamicTemplate(assign.size() - 1, baseWorkbook);
String wordRootPath = basePath + "/Electronic file transfer information package";
String dynamicTemplateFolderPath = basePath + "/Electronic file transfer information package/Other package";
File saveFile = new File(dynamicTemplateFolderPath);
if (!saveFile.exists()) {
saveFile.mkdirs();
}
String dynamicTemplatePath = dynamicTemplateFolderPath + "/电子档案移交清单" + DateUtil.format(new Date(), "yyyyMMddhhmmss") + ".xls";
//临时存储最终模板
FileOutputStream fos = null;
try {
fos = new FileOutputStream(dynamicTemplatePath);
dynamicWorkbook.write(fos);
dynamicWorkbook.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
TemplateExportParams params = new TemplateExportParams(dynamicTemplatePath);
Map<String, Object> map = new HashMap<String, Object>();
// 获取移交部门
String yjbm = "";
StringBuffer startToEndDh = new StringBuffer();
List<String> columnName = new ArrayList<>();
for (int i = 1; i <= assign.size(); i++) {
List<ZlkWjj> list = assign.get(i - 1);
List<Map> metaDataList = new ArrayList<>();
for (int j = 0; j < list.size(); j++) {
ZlkWjj zlkWjj = list.get(j);
if(StringUtils.isNotEmpty(zlkWjj.getYjbm())){
// 移交部门
yjbm = zlkWjj.getYjbm();
}
/**
* 2.构建全宗文件夹、元数据xml、原文文件
*/
File file = new File(wordRootPath + "/" + zlkWjj.getDalj());
if (!file.exists()) {
file.mkdirs();
}
String[] node = zlkWjj.getDalj().split("/");
metaDataList.add(ObjectUtil.beanToMap(zlkWjj));
String[] fieldNames = XmlUtil.getFiledName(zlkWjj);
for(int m=0 ; m<fieldNames.length ; m++){ //遍历所有属性
String name = fieldNames[m]; //获取属性的名字
columnName.add(name);
}
XmlUtil.createXmlFile(wordRootPath + "/" + zlkWjj.getDalj(), metaDataList, columnName,"电子档案"+ node[0] + "元数据", node[1], node[2]);
cn.hutool.core.io.FileUtil.copy(packagePath + "/" + zlkWjj.getQlj(), wordRootPath + "/" + zlkWjj.getDalj() + "/" + zlkWjj.getWjm(), true);
}
map.put("list" + i, list);
}
map.put("yjbm", yjbm);
map.put("yjsj", DateUtil.now());
//注入数据以及模板
Workbook workbook = ExcelExportUtil.exportExcel(params, map);
File saveFile1 = new File(dynamicTemplatePath);
FileOutputStream fos1 = new FileOutputStream(saveFile1);
workbook.write(fos1);
fos1.close();
/**
* 3、生成目录文件xml文件
*/
List<String> tableColumn = new ArrayList<>();
tableColumn.add("顺序号");
tableColumn.add("档号");
tableColumn.add("责任者");
tableColumn.add("题名");
tableColumn.add("日期");
tableColumn.add("保管期限");
tableColumn.add("密级");
tableColumn.add("备注");
List<Map> dataChineseList = new ArrayList<>();
dataChineseList.addAll(dataList);
for (int i = 0; i < dataChineseList.size(); i++) {
dataChineseList.get(i).put("顺序号", i + 1);
dataChineseList.get(i).put("档号", dataChineseList.get(i).get("dh"));
dataChineseList.get(i).put("责任者", dataChineseList.get(i).get("admin_name"));
dataChineseList.get(i).put("主题名", dataChineseList.get(i).get("ztm"));
dataChineseList.get(i).put("日期", dataChineseList.get(i).get("create_time"));
dataChineseList.get(i).put("保管期限", dataChineseList.get(i).get("bgqx"));
dataChineseList.get(i).put("密级", dataChineseList.get(i).get("mj"));
dataChineseList.get(i).put("备注", dataChineseList.get(i).get("bz"));
}
XmlUtil.createXmlFile(basePath + "/Electronic file transfer information package", dataChineseList, tableColumn,"目录文件","文件目录","文件");
/**
* 4、说明文件txt
*/
if (null != dataChineseList && dataChineseList.size() > 0) {
for (int i = 0; i < dataChineseList.size(); i++) {
if (i == 0) {
startToEndDh.append(dataChineseList.get(i).get("dh"));
startToEndDh.append("~");
}
if (i + 1 == dataChineseList.size()) {
startToEndDh.append(dataChineseList.get(i).get("dh"));
}
}
}
electronicTransferReadMe(gdkItem, startToEndDh.toString(), basePath);
/**
* 5、导入库文件夹条目数据
*/
ExportParams exportParams=new ExportParams("导入库文件级表","导入库文件级表", ExcelType.HSSF);
exportParams.setStyle(ExcelStyleUtil.class);
List<SysCatalogDataConfig> sysCatalogDataConfigList = sysCatalogDataConfigService.findCatalogListByTableName(dataList.get(0).get("catalog_id").toString(),"sys_data_imp_list");
List<ExcelExportEntity> beanList = new ArrayList<ExcelExportEntity>();
sysCatalogDataConfigList.stream().forEach(e->{
beanList.add(new ExcelExportEntity(e.getNewName(),e.getOldColumnName()));
});
List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
zlkWjjList.stream().forEach(e->{
mapList.add(Convert.convert(Map.class,e));
});
try {
Workbook sheets = ExcelExportUtil.exportExcel(exportParams, beanList, mapList);
String fileName = "导入库文件级表.xls";
FileOutputStream outputStream = new FileOutputStream(basePath + "/Electronic file transfer information package/" + fileName);
sheets.write(outputStream); // 写入磁盘
outputStream.close();
sheets.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 电子档案移交接收登记表
* @param gdkItem
* @param basePath
* @throws InvocationTargetException
* @throws IllegalAccessException
* @throws NoSuchMethodException
*/
public void electronicTransferRegister(GdkItem gdkItem, String basePath) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
//日期格式切换
if (StringUtils.isNotBlank(gdkItem.getReceiveExamineTime())){
gdkItem.setReceiveExamineTime(DateUtil.format(DateUtil.parse(gdkItem.getReceiveExamineTime(),"yyyy-MM-dd"),"yyyy 年 MM 月 dd 日"));
}
if (StringUtils.isNotBlank(gdkItem.getReceiveFilledTime())){
gdkItem.setReceiveFilledTime(DateUtil.format(DateUtil.parse(gdkItem.getReceiveFilledTime(),"yyyy-MM-dd"),"yyyy 年 MM 月 dd 日"));
}
if (StringUtils.isNotBlank(gdkItem.getReceiveSealTime())){
gdkItem.setReceiveSealTime(DateUtil.format(DateUtil.parse(gdkItem.getReceiveSealTime(),"yyyy-MM-dd"),"yyyy 年 MM 月 dd 日"));
}
if (StringUtils.isNotBlank(gdkItem.getRemoveExamineTime())){
gdkItem.setRemoveExamineTime(DateUtil.format(DateUtil.parse(gdkItem.getRemoveExamineTime(),"yyyy-MM-dd"),"yyyy 年 MM 月 dd 日"));
}
if (StringUtils.isNotBlank(gdkItem.getRemoveFilledTime())){
gdkItem.setRemoveFilledTime(DateUtil.format(DateUtil.parse(gdkItem.getRemoveFilledTime(),"yyyy-MM-dd"),"yyyy 年 MM 月 dd 日"));
}
if (StringUtils.isNotBlank(gdkItem.getRemoveSealTime())){
gdkItem.setRemoveSealTime(DateUtil.format(DateUtil.parse(gdkItem.getRemoveSealTime(),"yyyy-MM-dd"),"yyyy 年 MM 月 dd 日"));
}
String newPath = basePath + "/Electronic file transfer information package/Other package/";
String fileName = "电子档案移交接收登记表" + DateUtil.format(new Date(),"yyyyMMddHHmmss") + ".pdf";
Map<String,Object> dataMap = BeanUtils.describe(gdkItem);
pdfUtils.createYJRegisterPdf(dataMap,newPath,fileName);
}
/**
* 说明文件
* @param gdkItem
* @param startToEndDh
* @param basePath
*/
public void electronicTransferReadMe(GdkItem gdkItem, String startToEndDh, String basePath) {
if (Objects.nonNull(gdkItem)) {
StringBuffer text = new StringBuffer();
text.append("载体容量:" );
text.append("\r\n" );
if (null == gdkItem.getCarrierType()) {
text.append("载体类型:" );
} else {
text.append("载体类型:" + gdkItem.getCarrierType());
}
text.append("\r\n" );
text.append("载体编号:" );
text.append("\r\n" );
text.append("载体制作单位:" );
text.append("\r\n" );
if (null == gdkItem.getUnitName()) {
text.append("载体检查单位:" );
} else {
text.append("载体检查单位:" + gdkItem.getUnitName());
}
text.append("\r\n" );
if (null == gdkItem.getUnitName()) {
text.append("载体移交单位:" );
} else {
text.append("载体移交单位:" + gdkItem.getUnitName());
}
text.append("\r\n" );
if (null == gdkItem.getRemark()) {
text.append("内容描述:" );
} else {
text.append("内容描述:" + gdkItem.getRemark());
}
text.append("\r\n" );
text.append("起止档号:" + startToEndDh);
text.append("\r\n" );
if (null == gdkItem.getArchivesNum()) {
text.append("档案数量:" );
} else {
text.append("档案数量:" + gdkItem.getArchivesNum());
}
text.append("\r\n" );
text.append("软硬件环境:");
text.append("\r\n" );
text.append("其他:");
TxtUtil.exportTxt(basePath + "/Electronic file transfer information package", "说明文件.txt", text.toString());
}
}
/**
* 打包导出
* @param response
* @param id
*/
public void exportInfoZip(HttpServletResponse response, String id) {
GdkItem gdkItemById = findGdkItemById(id);
if (Objects.nonNull(gdkItemById)) {
String path = transferPath + "/" + gdkItemById.getZipInfo();
try {
// path是指想要下载的文件的路径
File file = new File(path);
// 获取文件名
String filename = file.getName();
// 将文件写入输入流
FileInputStream fileInputStream = new FileInputStream(file);
InputStream fis = new BufferedInputStream(fileInputStream);
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 清空response
response.reset();
// 设置response的Header
response.setCharacterEncoding("UTF-8");
//Content-Disposition的作用:告知浏览器以何种方式显示响应返回的文件,用浏览器打开还是以附件的形式下载到本地保存
//attachment表示以附件方式下载 inline表示在线打开 "Content-Disposition: inline; filename=文件名.mp3"
// filename表示文件的默认名称,因为网络传输只支持URL编码的相关支付,因此需要将文件名URL编码后进行传输,前端收到后需要反编码才能获取到真正的名称
response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
// 告知浏览器文件的大小
response.addHeader("Content-Length", "" + file.length());
OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
outputStream.write(buffer);
outputStream.flush();
} catch (IOException ex) {
ex.printStackTrace();
}
}
/**
* @author linc
* @Description 生成xml文件
* @date 2022/12/30
*/
public class XmlUtil {
/**
* 生成xml文件
* @param path 路径
* @param dataList 数据集合,键值对格式
* @param columnName 列名集合
* @param fileName xml文件名
* @param firstRootName xml根标签名称
* @param secondRootName xml子标签名称
*/
public static void createXmlFile(String path, List<Map> dataList,List<String> columnName,String fileName,String firstRootName,String secondRootName){
XMLWriter writer = null;
try {
// 生成一个Document对象
Document doc = DocumentHelper.createDocument();
// 添加根元素
Element root = doc.addElement(firstRootName);
// 为根元素添加子元素
for (Map dataMap : dataList) {
// 二级根元素名称
Element rootSecond = root.addElement(secondRootName);
for (String column : columnName) {
// 修改column的命名方式 user_id -> userId
String newColumn = changeName(column);
// 通过列名去键值对中查找值
if (null == dataMap.get(newColumn)) {
rootSecond.addElement(newColumn).setText("");
} else {
rootSecond.addElement(newColumn).setText(String.valueOf(dataMap.get(newColumn)));
}
}
}
File file = new File(path);
if (!file.exists()) {
file.mkdir();
}
// 输出xml文件
OutputFormat format = OutputFormat.createPrettyPrint();
writer = new XMLWriter(new OutputStreamWriter(new FileOutputStream(path + "/"+fileName+".xml"),"UTF-8"),format);
writer.write(doc);
} catch (IOException e) {
e.printStackTrace();
}finally {
// 关闭资源
try {
if (writer != null) {
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 修改数据库列名的命名
* @param str 修改前列名
* @return 下划线去掉,下划线后面的字母改大写,第一个字母改小写
*/
private static String changeName(String str) {
// 字符缓冲区
StringBuffer sbf = new StringBuffer();
// 如果列名带有-,也去掉
str = str.replaceAll("-", "_");
// 如果字符串包换下划线
if (str.contains("_")) {
// 通过下划线将字符串分隔为数组
String[] split = str.split("_");
// 循环数组操作其中的字符串
for (String s : split) {
if (s.length()>0) {
char[] ch = s.toCharArray();
if (ch[0] >= 'a' && ch[0] <= 'z') {
ch[0] = (char) (ch[0] - 32);
}
// 添加到字符缓冲
sbf.append(ch);
}
}
}else {
sbf.append(str);
}
// 将最后得到的字符串的首字母改成小写
char[] ch = sbf.toString().toCharArray();
if (ch[0] >= 'A' && ch[0] <= 'Z') {
ch[0] = (char) (ch[0] + 32);
}
return String.valueOf(ch);
}
/**
* 获取属性名数组
* */
public static String[] getFiledName(Object o){
Field[] fields=o.getClass().getDeclaredFields();
String[] fieldNames=new String[fields.length];
for(int i=0;i<fields.length;i++){
fieldNames[i]=fields[i].getName();
}
return fieldNames;
}
}