From 84af0838550ca618bac7c5552497e8b952cf1c6d Mon Sep 17 00:00:00 2001 From: yujh_java Date: Sat, 20 Sep 2025 20:42:48 +0800 Subject: [PATCH] =?UTF-8?q?=E5=90=88=E5=B9=B6test=E5=88=86=E6=94=AF?= =?UTF-8?q?=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../pal/pal/output/util/OutputWordUtil.java | 3163 +++++++++++------ 1 file changed, 2089 insertions(+), 1074 deletions(-) diff --git a/com.actionsoft.apps.coe.pal/src/com/actionsoft/apps/coe/pal/pal/output/util/OutputWordUtil.java b/com.actionsoft.apps.coe.pal/src/com/actionsoft/apps/coe/pal/pal/output/util/OutputWordUtil.java index ba1012c3..cd3a8675 100644 --- a/com.actionsoft.apps.coe.pal/src/com/actionsoft/apps/coe/pal/pal/output/util/OutputWordUtil.java +++ b/com.actionsoft.apps.coe.pal/src/com/actionsoft/apps/coe/pal/pal/output/util/OutputWordUtil.java @@ -1,5 +1,6 @@ package com.actionsoft.apps.coe.pal.pal.output.util; +import com.actionsoft.apps.coe.pal.constant.CoEConstant; import com.actionsoft.apps.coe.pal.constant.YiliWpsConst; import com.actionsoft.apps.coe.pal.pal.method.cache.PALMethodCache; import com.actionsoft.apps.coe.pal.pal.method.model.PALMethodAttributeModel; @@ -14,205 +15,149 @@ import com.actionsoft.apps.coe.pal.pal.repository.designer.relation.model.Design import com.actionsoft.apps.coe.pal.pal.repository.designer.util.CoeDesignerUtil; import com.actionsoft.apps.coe.pal.pal.repository.model.PALRepositoryModel; import com.actionsoft.apps.coe.pal.pal.repository.model.PALRepositoryPropertyModel; +import com.actionsoft.apps.coe.pal.pal.repository.upfile.constant.CoeFileConstant; import com.actionsoft.apps.coe.pal.pal.repository.upfile.dao.UpFileDao; import com.actionsoft.apps.coe.pal.pal.repository.upfile.model.UpfileModel; import com.actionsoft.apps.coe.pal.pal.ws.web.VersionUtil; import com.actionsoft.apps.coe.pal.util.HttpPostUtil; import com.actionsoft.apps.coe.pal.util.WPS4Util; import com.actionsoft.apps.resource.plugin.profile.DCPluginProfile; -import com.actionsoft.bpms.commons.database.RowMap; +import com.actionsoft.bpms.bo.engine.BO; +import com.actionsoft.bpms.commons.formfile.model.delegate.FormFile; import com.actionsoft.bpms.commons.mvc.view.ResponseObject; import com.actionsoft.bpms.org.model.DepartmentModel; import com.actionsoft.bpms.org.model.RoleModel; import com.actionsoft.bpms.org.model.UserModel; +import com.actionsoft.bpms.server.AWSServer; import com.actionsoft.bpms.server.DispatcherRequest; import com.actionsoft.bpms.server.UserContext; +import com.actionsoft.bpms.server.conf.portal.AWSPortalConf; import com.actionsoft.bpms.server.fs.DCContext; import com.actionsoft.bpms.server.fs.dc.DCProfileManager; -import com.actionsoft.bpms.util.DBSql; -import com.actionsoft.bpms.util.UUIDGener; -import com.actionsoft.bpms.util.UtilDate; -import com.actionsoft.bpms.util.UtilFile; -import com.actionsoft.bpms.util.UtilNumber; -import com.actionsoft.bpms.util.UtilString; +import com.actionsoft.bpms.util.*; import com.actionsoft.sdk.local.SDK; import com.actionsoft.sdk.local.api.AppAPI; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; -import com.google.gson.JsonObject; +//import com.aspose.words.TableAlignment; import com.sini.com.spire.doc.*; +import com.sini.com.spire.doc.collections.ParagraphCollection; import com.sini.com.spire.doc.collections.SectionCollection; import com.sini.com.spire.doc.documents.*; import com.sini.com.spire.doc.fields.DocPicture; -import com.sini.com.spire.doc.fields.ParagraphBase; import com.sini.com.spire.doc.fields.TextRange; import com.sini.com.spire.doc.formatting.CharacterFormat; import com.sini.com.spire.doc.formatting.ParagraphFormat; -import com.sini.com.spire.doc.interfaces.IDocument; -import com.sini.com.spire.doc.interfaces.IDocumentObject; +import com.sini.com.spire.doc.formatting.RowFormat; import com.sini.com.spire.doc.interfaces.IParagraph; import com.sini.com.spire.doc.interfaces.ITextRange; import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateException; -import java.awt.Color; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStreamWriter; -import java.io.Writer; +import org.apache.commons.lang.StringUtils; +import org.apache.pdfbox.text.TextPosition; + +import java.awt.*; +import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.StandardCharsets; import java.sql.Timestamp; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedHashSet; -import java.util.LinkedList; +import java.text.SimpleDateFormat; import java.util.List; -import java.util.Map; -import java.util.Set; +import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; +import static com.sini.com.spire.doc.documents.HorizontalAlignment.*; + public class OutputWordUtil { - public static final String DEPARTMENT = "department"; - public static final String POSITION = "position"; + public static final String DEPARTMENT = "department"; // 部门 + public static final String POSITION = "position"; // 岗位 + public static final String COMPANY = "company"; // 公司 + public static final String GENERATEDATE = "generate_date"; // 文档创建日期 + public static final String ORGDUTIE = "org_dutie"; // 岗位职责 - public static final String COMPANY = "company"; - - public static final String GENERATEDATE = "generate_date"; - - public static final String ORGDUTIE = "org_dutie"; - - public static final String TABLE_REPOSITORY = "repository_table"; - - public static final String TABLE_REPOSITORY_SHAPE = "repository_shape_table"; - - public static final String TABLE_INSTITUTION = "institution_table"; - - public static final String TABLE_FORM = "form_table"; - - public static final String TABLE_IT_SYSTEM = "itsystem_table"; - - public static final String TABLE_KPI = "KPI_table"; - - public static final String TABLE_DANGER = "danger_table"; - - public static final String TABLE_REGULATE = "regulate_table"; - - public static final String REPOSITORY_NAME = "repository_name"; - - public static final String PL_NUMBER = "pl_number"; - - public static final String PL_RESPONSIBLE_PERSON = "pl_responsible_person"; - - public static final String PL_RESPONSIBLE_DEPARTMENT = "pl_responsible_department"; - - public static final String PL_EXECUTIVE_ARM = "pl_executive_arm"; - - public static final String PL_INPUT = "pl_input"; - - public static final String PL_OUTPUT = "pl_output"; - - public static final String PL_DESC = "pl_desc"; - - public static final String PL_CREATE_USER = "pl_create_user"; - - public static final String PL_VERSION = "pl_version"; - - public static final String PL_RESPONSIBILITY = "pl_responsibility"; - - public static final String PL_BUSINESS = "pl_business"; - - public static final String PL_LEAD_PROCESS = "pl_lead_process"; - - public static final String PL_REAR_PROCESS = "pl_rear_process"; - - public static final String PL_ITSYSTEM = "pl_itsystem"; - - public static final String PL_DIAGRAM = "pl_diagram"; - - public static final String PL_DIAGRAM_WIDTH = "pl_diagram_width"; - - public static final String PL_DIAGRAM_HEIGHT = "pl_diagram_height"; + public static final String TABLE_REPOSITORY = "repository_table"; // 流程table + public static final String TABLE_REPOSITORY_SHAPE = "repository_shape_table"; // 流程步骤table + public static final String TABLE_INSTITUTION = "institution_table"; // 制度table + public static final String TABLE_FORM = "form_table"; // 表单table + public static final String TABLE_IT_SYSTEM = "itsystem_table"; // 信息系统table + public static final String TABLE_KPI = "KPI_table"; // 绩效table + public static final String TABLE_DANGER = "danger_table"; // 风控要求table + public static final String TABLE_REGULATE = "regulate_table"; // 风控(控制)要求table + public static final String REPOSITORY_NAME = "repository_name"; // 流程名 + public static final String PL_NUMBER = "pl_number"; // 流程编号 + public static final String PL_RESPONSIBLE_PERSON = "pl_responsible_person"; // 责任人 + public static final String PL_RESPONSIBLE_DEPARTMENT = "pl_responsible_department"; // 责任部门 + public static final String PL_EXECUTIVE_ARM = "pl_executive_arm"; // 流程执行部门 + public static final String PL_INPUT = "pl_input"; // 流程输入 + public static final String PL_OUTPUT = "pl_output"; // 流程输出 + public static final String PL_DESC = "pl_desc"; // 流程说明 + public static final String PL_CREATE_USER = "pl_create_user"; // 编制人 + public static final String PL_VERSION = "pl_version"; // 版本号 + public static final String PL_RESPONSIBILITY = "pl_responsibility"; // 主要人员职责描述 + public static final String PL_BUSINESS = "pl_business"; // 关键业务逻辑规则 + public static final String PL_LEAD_PROCESS = "pl_lead_process"; // 前置流程 + public static final String PL_REAR_PROCESS = "pl_rear_process"; // 后置流程 + public static final String PL_ITSYSTEM = "pl_itsystem"; // 相关IT系统 + public static final String PL_DIAGRAM = "pl_diagram"; // 流程图 + public static final String PL_DIAGRAM_WIDTH = "pl_diagram_width"; // 流程图宽度 + public static final String PL_DIAGRAM_HEIGHT = "pl_diagram_height"; // 流程图高度 public static final int PL_DIAGRAM_MAX_WIDTH = 480; - public static final int PL_DIAGRAM_MAX_HEIGHT = 676; - public static final String SERIAL_NUMBER = "serial_number"; + public static final String SERIAL_NUMBER = "serial_number"; // 序号 + public static final String SHAPE_ID = "shape_id"; // 流程图形元素id + public static final String SHAPE_NAME = "shape_name"; // 流程图形元素名称 + public static final String SHAPE_NUMBER = "shape_number"; // 步骤编号 + public static final String SHAPE_DESC = "shape_desc"; // 工作详细描述 + public static final String SHAPE_INSTITUTION = "shape_institution"; // 制度要求 + public static final String SHAPE_DANGER = "shape_danger"; // 风险点 + public static final String SHAPE_KPI = "shape_kpi"; // 指标 + public static final String SHAPE_FORM = "shape_form"; // 作业单据 + public static final String SHAPE_HANDLE_TIME = "shape_handle_time"; // 处理时间 + public static final String SHAPE_ITSYSTEM = "shape_itsystem"; // 信息系统 + public static final String SHAPE_VERSION = "shape_version"; // 版本号 + public static final String SHAPE_APPLICATION_SCOPE = "shape_application_scope"; // 适用范围 + public static final String SHAPE_TARGET_VALUE = "shape_target_value"; // 指标值 + public static final String SHAPE_DUTY_R = "shape_duty_r"; // 责任者 - public static final String SHAPE_ID = "shape_id"; + public static final String SHAPE_BUSINESS = "shape_business";// 业务规则 + public static final String SHAPE_INPUT = "shape_input";// 输入 + public static final String SHAPE_OUT = "shape_out";// 输出 - public static final String SHAPE_NAME = "shape_name"; - - public static final String SHAPE_NUMBER = "shape_number"; - - public static final String SHAPE_DESC = "shape_desc"; - - public static final String SHAPE_INSTITUTION = "shape_institution"; - - public static final String SHAPE_DANGER = "shape_danger"; - - public static final String SHAPE_KPI = "shape_kpi"; - - public static final String SHAPE_FORM = "shape_form"; - - public static final String SHAPE_HANDLE_TIME = "shape_handle_time"; - - public static final String SHAPE_ITSYSTEM = "shape_itsystem"; - - public static final String SHAPE_VERSION = "shape_version"; - - public static final String SHAPE_APPLICATION_SCOPE = "shape_application_scope"; - - public static final String SHAPE_TARGET_VALUE = "shape_target_value"; - - public static final String SHAPE_DUTY_R = "shape_duty_r"; - - public static final String SHAPE_BUSINESS = "shape_business"; - - public static final String SHAPE_INPUT = "shape_input"; - - public static final String SHAPE_OUT = "shape_out"; - - public static final String SHAPE_EFFECT = "shape_effect"; - - public static final String SHAPE_PROBABILITY = "shape_probability"; - - public static final String SHAPE_TARGET = "shape_target"; - - public static final String SHAPE_FREQUENCY = "shape_frequency"; - - public static final String SHAPE_MEASURE = "shape_measure"; - - public static final String SHAPE_CALCULATION_METHOD = "shape_calculation_method"; - - public static final String SHAPE_CALCULATION_PROPORTION = "shape_calculation_proportion"; - - public static final String SHAPE_CALCULATION_FREQUENCY = "shape_calculation_frequency"; - - public static final String SHAPE_RELATION_NAME = "shape_relation_name"; + public static final String SHAPE_EFFECT = "shape_effect"; // 风险影响 + public static final String SHAPE_PROBABILITY = "shape_probability"; // 风险概率 + public static final String SHAPE_TARGET = "shape_target"; // 控制目标 + public static final String SHAPE_FREQUENCY = "shape_frequency"; // 控制频率 + public static final String SHAPE_MEASURE = "shape_measure"; // 控制措施 + public static final String SHAPE_CALCULATION_METHOD = "shape_calculation_method"; // 计算公式 + public static final String SHAPE_CALCULATION_PROPORTION = "shape_calculation_proportion"; // 计算比例 + public static final String SHAPE_CALCULATION_FREQUENCY = "shape_calculation_frequency"; // 计算频率 + public static final String SHAPE_RELATION_NAME = "shape_relation_name"; // 关联性质名 + //word换行符 public static final String WRAPSTRING = ""; + /** + * 生成word文件 + * + * @param dataMap + * @param tempPath + * @param tempName + * @param docName + */ public static void createDoc(JSONObject dataMap, String tempPath, String tempName, String docName) { Configuration configuration = new Configuration(); configuration.setDefaultEncoding("UTF-8"); + + // 设置模本装置方法和路径 try { UtilFile temps = new UtilFile(tempPath); - configuration.setDirectoryForTemplateLoading((File)temps); + configuration.setDirectoryForTemplateLoading(temps); } catch (IOException e2) { e2.printStackTrace(); } @@ -222,6 +167,7 @@ public class OutputWordUtil { } catch (IOException e) { e.printStackTrace(); } + // 输出文档路径及名称 File outFile = new File(docName); Writer out = null; try { @@ -229,6 +175,7 @@ public class OutputWordUtil { } catch (Exception e1) { e1.printStackTrace(); } + try { t.process(dataMap, out); out.flush(); @@ -240,12 +187,22 @@ public class OutputWordUtil { } } - public static void createDoc2(JSONObject dataMap, String tempPath, String tempName, String docName, String repositoryId) throws FileNotFoundException { + /** + * 生成word文件 + * + * @param dataMap + * @param tempPath + * @param tempName + * @param docName + */ + public static void createDoc2(JSONObject dataMap, String tempPath, String tempName, String docName,String repositoryId) throws FileNotFoundException { Configuration configuration = new Configuration(); configuration.setDefaultEncoding("UTF-8"); + + // 设置模本装置方法和路径 try { UtilFile temps = new UtilFile(tempPath); - configuration.setDirectoryForTemplateLoading((File)temps); + configuration.setDirectoryForTemplateLoading(temps); } catch (IOException e2) { e2.printStackTrace(); } @@ -255,6 +212,9 @@ public class OutputWordUtil { } catch (IOException e) { e.printStackTrace(); } + + + // 输出文档路径及名称 File outFile = new File(docName); Writer out = null; try { @@ -262,6 +222,7 @@ public class OutputWordUtil { } catch (Exception e1) { e1.printStackTrace(); } + try { if (t != null && out != null) { t.process(dataMap, out); @@ -273,6 +234,11 @@ public class OutputWordUtil { } catch (IOException e) { e.printStackTrace(); } + + //流程图新增逻辑,增加管理要求wps文件合并需求 + mergeMRWord(outFile.getPath(),repositoryId,dataMap); + + Document doc = new Document(outFile.getPath()); Section section = doc.getLastSection(); UpFileDao upFileDao = new UpFileDao(); @@ -280,104 +246,103 @@ public class OutputWordUtil { PALRepositoryModel repositoryModel = PALRepositoryQueryAPIManager.getInstance().queryPalRepositoryModelByPalId(repositoryId); DCContext dcContextModel = null; List search = upFileDao.searchByRepositoryId(repositoryModel.getId(), "f"); + //读取模型附件插入手册中文档对象 if (search != null && search.size() > 0) { + //插入前,附件名先排序先排序 sortFilesByNumber(search); + //附件如果为空,不插入附件标题 CharacterFormat format4 = new CharacterFormat(); + //创建字体格式 format4.setFontName("宋体"); + //添加段落 Paragraph paragraph4 = section.addParagraph(); + ParagraphFormat paragraphFormat4 = paragraph4.getFormat(); - paragraphFormat4.setHorizontalAlignment(HorizontalAlignment.Left); + paragraphFormat4.setHorizontalAlignment(Left); + TextRange tr4 = paragraph4.appendText("附件"); + + tr4.getCharacterFormat().setBold(true); tr4.getCharacterFormat().setFontName("宋体"); - tr4.getCharacterFormat().setFontSize(12.0F); - paragraph4.applyStyle(BuiltinStyle.Body_Text); + tr4.getCharacterFormat().setFontSize(12); + paragraph4.applyStyle(BuiltinStyle.Body_Text); //应用标题1样式 + long b1 = System.currentTimeMillis(); for (UpfileModel upfileModel : search) { - DCPluginProfile dcProfile = DCProfileManager.getDCProfile("com.actionsoft.apps.coe.pal", "COE_Upfile"); + DCPluginProfile dcProfile = DCProfileManager.getDCProfile(CoEConstant.APP_ID, CoeFileConstant.COE_UPFILE); if (dcProfile != null) { - dcContextModel = new DCContext(userContext, dcProfile, "com.actionsoft.apps.coe.pal", "file", upfileModel.getPl_uuid(), upfileModel.getFileName()); + + // 处理DocCenter + dcContextModel = new DCContext(userContext, dcProfile, CoEConstant.APP_ID, "file", upfileModel.getPl_uuid(), upfileModel.getFileName()); + //添加段落 Paragraph paragraph5 = section.addParagraph(); + //加载一个图片,它将作为外部文件的符号显示在Word文档中 + //获取最后一个.的位置 int lastIndexOf = dcContextModel.getFileName().lastIndexOf("."); + //获取文件的后缀名 .jpg String suffix = dcContextModel.getFileName().substring(lastIndexOf); - DocPicture pdfIcon = new DocPicture((IDocument)doc); + + DocPicture pdfIcon = new DocPicture(doc); + InputStream stream1 = new FileInputStream(dcContextModel.getFilePath()); - DocPicture pic1 = new DocPicture((IDocument)doc); + DocPicture pic1 = new DocPicture(doc); + if (suffix.equals(".doc") || suffix.equals(".docx")) { pic1.loadImage("../doccenter/com.awspaas.user.apps.coe.pal.output.zd/filepic/word.png"); - paragraph5.appendText(dcContextModel.getFileName() + " "); + paragraph5.appendText(dcContextModel.getFileName()+" "); if (suffix.equals(".doc")) { paragraph5.appendOleObject(stream1, pic1, "doc"); - continue; - } - if (suffix.equals(".docx")) + } else if (suffix.equals(".docx")) { paragraph5.appendOleObject(stream1, pic1, "docx"); - continue; - } - if (suffix.equals(".pdf")) { + } + } else if (suffix.equals(".pdf")) { pic1.loadImage("../doccenter/com.awspaas.user.apps.coe.pal.output.zd/filepic/pdf.png"); - paragraph5.appendText(dcContextModel.getFileName() + " "); + paragraph5.appendText(dcContextModel.getFileName()+" "); paragraph5.appendOleObject(stream1, pic1, "pdf"); - continue; - } - if (suffix.equals(".xls") || suffix.equals(".xlsx")) { + } else if (suffix.equals(".xls") || suffix.equals(".xlsx")) { pic1.loadImage("../doccenter/com.awspaas.user.apps.coe.pal.output.zd/filepic/xls.png"); - paragraph5.appendText(dcContextModel.getFileName() + " "); + paragraph5.appendText(dcContextModel.getFileName()+" "); if (suffix.equals(".xls")) { paragraph5.appendOleObject(stream1, pic1, "xls"); - continue; - } - if (suffix.equals(".xlsx")) + } else if (suffix.equals(".xlsx")) { paragraph5.appendOleObject(stream1, pic1, "xlsx"); - continue; - } - if (suffix.equals(".png") || suffix.equals(".jgp")) { + } + } else if (suffix.equals(".png") || suffix.equals(".jgp")) { pic1.loadImage("../doccenter/com.awspaas.user.apps.coe.pal.output.zd/filepic/png.png"); - paragraph5.appendText(dcContextModel.getFileName() + " "); + paragraph5.appendText(dcContextModel.getFileName()+" "); if (suffix.equals(".png")) { paragraph5.appendOleObject(stream1, pic1, "png"); - continue; - } - if (suffix.equals(".jpg")) + } else if (suffix.equals(".jpg")) { paragraph5.appendOleObject(stream1, pic1, "jpg"); - continue; - } - if (suffix.equals(".zip") || suffix.equals(".rar")) { + } + } else if (suffix.equals(".zip") || suffix.equals(".rar")) { pic1.loadImage("../doccenter/com.awspaas.user.apps.coe.pal.output.zd/filepic/zip.png"); - paragraph5.appendText(dcContextModel.getFileName() + " "); + paragraph5.appendText(dcContextModel.getFileName()+" "); if (suffix.equals(".zip")) { paragraph5.appendOleObject(stream1, pic1, "zip"); - continue; - } - if (suffix.equals(".rar")) + } else if (suffix.equals(".rar")) { paragraph5.appendOleObject(stream1, pic1, "rar"); - continue; - } - if (suffix.equals(".mp3") || suffix.equals(".mp4")) { + } + } else if (suffix.equals(".mp3") || suffix.equals(".mp4")) { pic1.loadImage("../doccenter/com.awspaas.user.apps.coe.pal.output.zd/filepic/mp3.png"); - paragraph5.appendText(dcContextModel.getFileName() + " "); + paragraph5.appendText(dcContextModel.getFileName()+" "); if (suffix.equals(".mp3")) { paragraph5.appendOleObject(stream1, pic1, "mp3"); - continue; - } - if (suffix.equals(".mp4")) + } else if (suffix.equals(".mp4")) { paragraph5.appendOleObject(stream1, pic1, "mp4"); - continue; - } - if (suffix.equals(".ppt") || suffix.equals(".pptx")) { + } + } else if (suffix.equals(".ppt") || suffix.equals(".pptx")) { pic1.loadImage("../doccenter/com.awspaas.user.apps.coe.pal.output.zd/filepic/ppt.png"); - paragraph5.appendText(dcContextModel.getFileName() + " "); + paragraph5.appendText(dcContextModel.getFileName()+" "); if (suffix.equals(".ppt")) { paragraph5.appendOleObject(stream1, pic1, "ppt"); - continue; - } - if (suffix.equals(".pptx")) + } else if (suffix.equals(".pptx")) { paragraph5.appendOleObject(stream1, pic1, "pptx"); - continue; - } - if (suffix.equals(".txt")) { + } + } else if (suffix.equals(".txt")) { pic1.loadImage("../doccenter/com.awspaas.user.apps.coe.pal.output.zd/filepic/txt.png"); - paragraph5.appendText(dcContextModel.getFileName() + " "); + paragraph5.appendText(dcContextModel.getFileName()+" "); paragraph5.appendOleObject(stream1, pic1, "txt"); } } @@ -387,17 +352,32 @@ public class OutputWordUtil { } catch (Exception e) { e.printStackTrace(); } finally { + // 关闭文档对象 doc.close(); } } + + } - public static void createZdDoc2(JSONObject dataMap, String tempPath, String tempName, String docName, JSONObject wizardJsonData, String repositoryId, String docPath) throws FileNotFoundException { - Configuration configuration = new Configuration(); + + /** + * oa审批审批流程创建word + * @param dataMap + * @param tempPath + * @param tempName + * @param docName + * @param repositoryId + * @throws FileNotFoundException + */ + public static void createOAApproveDoc(JSONObject dataMap, String tempPath, String tempName, String docName,String repositoryId) throws FileNotFoundException { + Configuration configuration = new Configuration(); configuration.setDefaultEncoding("UTF-8"); + + // 设置模本装置方法和路径 try { UtilFile temps = new UtilFile(tempPath); - configuration.setDirectoryForTemplateLoading((File)temps); + configuration.setDirectoryForTemplateLoading(temps); } catch (IOException e2) { e2.printStackTrace(); } @@ -407,69 +387,369 @@ public class OutputWordUtil { } catch (IOException e) { e.printStackTrace(); } - List> repositoryFileElements = CoeDesignerUtil.getShapeMessageJson4(repositoryId); - if (wizardJsonData.getBoolean("orderNuberFirst").booleanValue()) - orderByNumber(repositoryFileElements); + + + // 输出文档路径及名称 + File outFile = new File(docName); + Writer out = null; + try { + out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8")); + } catch (Exception e1) { + e1.printStackTrace(); + } + + try { + if (t != null && out != null) { + t.process(dataMap, out); + out.flush(); + out.close(); + } + } catch (TemplateException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + + + BO oaapprovalBO = SDK.getBOAPI().getByKeyField("BO_EU_OA_APPROVAL_TEMPLATE_TJ", "FILEUUID", repositoryId); + if (null == oaapprovalBO || !"1".equals(oaapprovalBO.getString("STATUS"))) { + return; + } + + List processfile = SDK.getBOAPI().getFiles(oaapprovalBO.getId(), "PROCESSFILE"); + if (processfile.isEmpty()) { + return; + } + FormFile formFile = processfile.get(0); + DCContext fileDCContext = SDK.getBOAPI().getFileDCContext(formFile); + + // 加载目标文件和待合并文档2 + Document docs1 = new Document(); + docs1.loadFromFile(outFile.getPath()); + Document docs2 = new Document(); + docs2.loadFromFile(fileDCContext.getFilePath()); + + + Section lastSection1 = docs1.getLastSection(); + + // 删除最后一个节 + docs1.getSections().remove(lastSection1); + + // 提取所有表格 + List allTables = extractAllTables(docs2); + + if (allTables.size() >= 4) { + // 拆分表格:前2个表格,后2个表格 + List
firstTwoTables = allTables.subList(0, 1); + + TextPosition position = findTextPosition(docs1, "流程图"); + + if (position != null) { + // 在前面插入前2个表格 + insertTablesBeforeText(docs1, firstTwoTables, position); + + // 获取docs2中剩余的内容(除了前两个表格) + List remainingContent = extractRemainingContent(docs2, firstTwoTables.size()); + + // 将剩余内容插入到docs1的最后一节 + insertContentToLastSection(docs1, remainingContent); + + + // 保存合并后的文档 + docs1.saveToFile(outFile.getPath(), FileFormat.Docx); + + docs1.dispose(); + docs2.dispose(); + + System.out.println("文档合并成功!"); + } else { + System.out.println("未找到文本'流程图'"); + } + } else { + System.out.println("源文档中的表格数量不足4个,当前只有: " + allTables.size()); + } + + + + + + + + } + + + + + /** + * 提取剩余内容(除了前n个表格) + */ + private static List extractRemainingContent(Document document, int tablesToSkip) { + List remainingContent = new ArrayList<>(); + int skippedTables = 0; + + for (int i = 0; i < document.getSections().getCount(); i++) { + Section section = document.getSections().get(i); + for (int j = 0; j < section.getBody().getChildObjects().getCount(); j++) { + DocumentObject obj = section.getBody().getChildObjects().get(j); + + if (obj instanceof Table) { + if (skippedTables < tablesToSkip) { + skippedTables++; + continue; // 跳过前n个表格 + } + } + + // 克隆对象以避免重复引用问题 + remainingContent.add(obj.deepClone()); + } + } + return remainingContent; + } + + + + + /** + * 将内容插入到最后一节 + */ + private static void insertContentToLastSection(Document docs1, List content) { + int lastSectionIndex = docs1.getSections().getCount() - 1; + Section lastSection = docs1.getSections().get(lastSectionIndex); + + // 在插入前添加分页符(可选) + Paragraph pageBreak = new Paragraph(docs1); + pageBreak.appendBreak(BreakType.Page_Break); + lastSection.getBody().getChildObjects().add(pageBreak); + + // 插入剩余内容 + for (DocumentObject obj : content) { + lastSection.getBody().getChildObjects().add(obj); + } + } + + + + + /** + * 提取文档中的所有表格 + */ + private static List
extractAllTables(Document doc) { + List
tables = new ArrayList<>(); + + for (Object sectionObj : doc.getSections()) { + Section section = (Section) sectionObj; + + for (Object obj : section.getBody().getChildObjects()) { + if (obj instanceof Table) { + tables.add((Table) obj); + } + } + } + + return tables; + } + + /** + * 查找文本位置 + */ + private static TextPosition findTextPosition(Document doc, String targetText) { + for (int s = 0; s < doc.getSections().getCount(); s++) { + Section section = doc.getSections().get(s); + + for (int p = 0; p < section.getParagraphs().getCount(); p++) { + Paragraph paragraph = section.getParagraphs().get(p); + String paragraphText = paragraph.getText(); + + if (paragraphText.contains(targetText)) { + return new TextPosition(s, p, paragraphText.indexOf(targetText)); + } + } + } + return null; + } + + /** + * 在指定文本前插入表格 + */ + private static void insertTablesBeforeText(Document mainDoc, List
tables, TextPosition position) { + Section mainSection = mainDoc.getSections().get(position.getSectionIndex()); + Paragraph targetParagraph = mainSection.getParagraphs().get(position.getParagraphIndex()); + int insertIndex = mainSection.getBody().getChildObjects().indexOf(targetParagraph); + + // 在前方插入表格(反向插入以保持顺序) + for (int i = tables.size() - 1; i >= 0; i--) { + Table clonedTable = tables.get(i).deepClone(); + mainSection.getBody().getChildObjects().insert(insertIndex, clonedTable); + + // 在每个表格前添加一个空段落作为间隔 + Paragraph spacingPara = new Paragraph(mainDoc); + mainSection.getBody().getChildObjects().insert(insertIndex, spacingPara); + } + } + + /** + * 在指定文本后插入表格 + */ + private static void insertTablesAfterText(Document mainDoc, List
tables, TextPosition position) { + Section mainSection = mainDoc.getSections().get(position.getSectionIndex()); + Paragraph targetParagraph = mainSection.getParagraphs().get(position.getParagraphIndex()); + int insertIndex = mainSection.getBody().getChildObjects().indexOf(targetParagraph) + 1; + + // 在后方插入表格 + for (Table table : tables) { + Table clonedTable = table.deepClone(); + mainSection.getBody().getChildObjects().insert(insertIndex, clonedTable); + insertIndex++; + + // 在每个表格后添加一个空段落作为间隔 + Paragraph spacingPara = new Paragraph(mainDoc); + mainSection.getBody().getChildObjects().insert(insertIndex, spacingPara); + insertIndex++; + } + } + + /** + * 文本位置信息类 + */ + static class TextPosition { + private int sectionIndex; + private int paragraphIndex; + private int textOffset; + + public TextPosition(int sectionIndex, int paragraphIndex, int textOffset) { + this.sectionIndex = sectionIndex; + this.paragraphIndex = paragraphIndex; + this.textOffset = textOffset; + } + + public int getSectionIndex() { return sectionIndex; } + public int getParagraphIndex() { return paragraphIndex; } + public int getTextOffset() { return textOffset; } + } + + + /** + * 生成word文件 + * + * @param dataMap + * @param tempPath + * @param tempName + * @param docName + */ + public static void createZdDoc2(JSONObject dataMap, String tempPath, String tempName, String docName, JSONObject wizardJsonData, String repositoryId, String docPath) throws FileNotFoundException { + + Configuration configuration = new Configuration(); + configuration.setDefaultEncoding("UTF-8"); + + // 设置模本装置方法和路径 + try { + UtilFile temps = new UtilFile(tempPath); + configuration.setDirectoryForTemplateLoading(temps); + } catch (IOException e2) { + e2.printStackTrace(); + } + Template t = null; + try { + t = configuration.getTemplate(tempName, "UTF-8"); + } catch (IOException e) { + e.printStackTrace(); + } + +//***********************************************************使用spire 生成模板后复制文件****************************************************/ + List> repositoryFileElements = CoeDesignerUtil.getShapeMessageJson4(repositoryId); //流程文件内容 + if (wizardJsonData.getBoolean("orderNuberFirst")) { // 根据页面选择进行排序 + OutputWordUtil.orderByNumber(repositoryFileElements); + } + String controlShapeId = ""; if (repositoryFileElements != null) { - int index = 1; - int dangerIndex = 1; - int regulateIndex = 1; + int index = 1;// 流程步骤序号 + int dangerIndex = 1;// 风险序号 + int regulateIndex = 1;// 控制序号 for (Map shape : repositoryFileElements) { String type = shape.get("type").toString(); if ("regulation".equals(type)) { controlShapeId = shape.get("id").toString(); - continue; - } - if ("I/O_L4".equals(type)) { + } else if ("I/O_L4".equals(type)) { controlShapeId = shape.get("id").toString(); - continue; - } - if ("card".equals(type)) + } else if("card".equals(type)){ controlShapeId = shape.get("id").toString(); + } } } + + UserContext userContext = DispatcherRequest.getUserContext(); + Map result = new HashMap<>(); result.put("listDef", ""); result.put("content", ""); + PALRepositoryModel repositoryModel = PALRepositoryQueryAPIManager.getInstance().queryPalRepositoryModelByPalId(repositoryId); + String content = ""; StringBuilder listStr = new StringBuilder(); + // 读取附件 + // 流程附件列表 UpFileDao upFileDao = new UpFileDao(); List search = upFileDao.search(repositoryModel.getId(), controlShapeId, null); + DCContext dcContextpdf = null; File file = null; + boolean isPPT = false; + //如果为PPT,则生成PPT手册 if (search != null && search.size() > 0) { + //插入前,附件名先排序先排序 sortFilesByNumber(search); long b1 = System.currentTimeMillis(); + // 复制附件 for (UpfileModel upfileModel : search) { - DCPluginProfile dcProfile = DCProfileManager.getDCProfile("com.actionsoft.apps.coe.pal", "COE_Upfile"); + DCPluginProfile dcProfile = DCProfileManager.getDCProfile(CoEConstant.APP_ID, CoeFileConstant.COE_UPFILE); + if (dcProfile != null) { - dcContextpdf = new DCContext(userContext, dcProfile, "com.actionsoft.apps.coe.pal", upfileModel.getPl_uuid(), upfileModel.getShape_uuid(), upfileModel.getFileName()); + dcContextpdf = new DCContext(userContext, dcProfile, CoEConstant.APP_ID, upfileModel.getPl_uuid(), upfileModel.getShape_uuid(), upfileModel.getFileName()); String path = dcContextpdf.getPath(); String fileName = dcContextpdf.getFileName(); + String suffix = fileName.substring(fileName.lastIndexOf(".") + 1); if (suffix.equals("pptx")) { isPPT = true; String pptUrl = docName.substring(0, docName.lastIndexOf("/") + 1); + // 调用App String sourceAppId = "com.actionsoft.apps.coe.pal"; + // aslp服务地址 String aslp = "aslp://com.awspaas.user.apps.new_performance_indicator_library/UpdatePptxAndExcelAslp"; + // 参数定义列表 Map params = new HashMap(); + //文件id,必填 params.put("pl_uuid", repositoryId); + //文件内容id,必填 params.put("shape_uuid", search.get(0).getShape_uuid()); + + //文件保存地址,必填 params.put("fil_path", pptUrl + search.get(0).getFileName()); + + //文件路径(不包含文件名称),必填 params.put("file_url", pptUrl); + + //文件名称,必填 params.put("file_data", search.get(0).getFileName()); + //sid,必填 params.put("sid", userContext.getSessionId()); AppAPI appAPI = SDK.getAppAPI(); - ResponseObject responseObject = appAPI.callASLP(appAPI.getAppContext(sourceAppId), aslp, params); + //根据上传的文件进行更新相关的excel或者ppt + ResponseObject ro = appAPI.callASLP(appAPI.getAppContext(sourceAppId), aslp, params); + } + + } } } - if (!isPPT) { + + if (isPPT == false) { + // 输出文档路径及名称 File outFile = new File(docName); Writer out = null; try { @@ -477,6 +757,8 @@ public class OutputWordUtil { } catch (Exception e1) { e1.printStackTrace(); } + + try { if (t != null && out != null) { t.process(dataMap, out); @@ -488,59 +770,89 @@ public class OutputWordUtil { } catch (IOException e) { e.printStackTrace(); } + + if (search != null && search.size() > 0) { + //插入前,附件名先排序先排序 sortFilesByNumber(search); long b1 = System.currentTimeMillis(); + // 复制附件 for (UpfileModel upfileModel : search) { - DCPluginProfile dcProfile = DCProfileManager.getDCProfile("com.actionsoft.apps.coe.pal", "COE_Upfile"); + DCPluginProfile dcProfile = DCProfileManager.getDCProfile(CoEConstant.APP_ID, CoeFileConstant.COE_UPFILE); + if (dcProfile != null) { - dcContextpdf = new DCContext(userContext, dcProfile, "com.actionsoft.apps.coe.pal", upfileModel.getPl_uuid(), upfileModel.getShape_uuid(), upfileModel.getFileName()); + dcContextpdf = new DCContext(userContext, dcProfile, CoEConstant.APP_ID, upfileModel.getPl_uuid(), upfileModel.getShape_uuid(), upfileModel.getFileName()); String path = dcContextpdf.getPath(); String fileName = dcContextpdf.getFileName(); + + + //创建 Document 类的对象并从磁盘加载 Word 文档 Document document = new Document(outFile.getPath()); + // 获取第一个节的第一个表格 Section firstsection = document.getSections().get(1); Table table1 = firstsection.getTables().get(0); - table1.setPreferredWidth(new PreferredWidth(WidthType.Twip, (short)8335)); - for (int i = 0; i < table1.getRows().getCount(); i++) { + + + table1.setPreferredWidth(new PreferredWidth(WidthType.Twip, (short) 8335f)); + + //遍历表格单元格 + for (int i = 0;i< table1.getRows().getCount();i++) { TableRow rows = table1.getRows().get(i); - for (int k = 0; k < rows.getCells().getCount(); k++) { - for (int z = 0; z < rows.getCells().get(k).getParagraphs().getCount(); z++) { - Paragraph p = rows.getCells().get(k).getParagraphs().get(z); - p.getFormat().setLineSpacing(12.0F); - for (int m = 0; m < p.getItems().getCount(); m++) { - ParagraphBase paragraphBase = p.getItems().get(m); - if (paragraphBase instanceof TextRange) { - TextRange textRange = (TextRange)paragraphBase; + + + for (int j = 0; j< rows.getCells().getCount(); j++){ + for (int z= 0; z < rows.getCells().get(j).getParagraphs().getCount();z++){ + Paragraph p = rows.getCells().get(j).getParagraphs().get(z); + p.getFormat().setLineSpacing(12f);//设置边距为1.0 + for (int k = 0; k < p.getItems().getCount(); k++) { + DocumentObject item = p.getItems().get(k); + if (item instanceof TextRange) { + TextRange textRange = (TextRange) item; textRange.getCharacterFormat().setFontName("宋体"); - textRange.getCharacterFormat().setFontSize(10.5F); + textRange.getCharacterFormat().setFontSize(10.5f); } } + } } + } + + JSONArray versionHistoryTable = getVersionHistoryTable(repositoryModel); - int j = 0; + int index = 0; if (versionHistoryTable.getJSONObject(0).size() > 0) { - Section section1 = document.getLastSection(); + + //获取最后一节 + Section section = document.getLastSection(); + + CharacterFormat format2 = new CharacterFormat(); + //创建字体格式 format2.setFontName("宋体"); - Paragraph paragraph2 = section1.addParagraph(); + //添加段落,设置一级序列 + Paragraph paragraph2 = section.addParagraph(); ParagraphFormat paragraphFormat2 = paragraph2.getFormat(); - paragraphFormat2.setHorizontalAlignment(HorizontalAlignment.Left); + paragraphFormat2.setHorizontalAlignment(Left); TextRange tr2 = paragraph2.appendText("修订记录"); tr2.getCharacterFormat().setBold(true); tr2.getCharacterFormat().setFontName("宋体"); - tr2.getCharacterFormat().setFontSize(12.0F); - paragraph2.applyStyle(BuiltinStyle.Body_Text); - String[] header = { "版本", "发布部门", "拟制人", "拟制日期", "审核人", "复核人", "审批人", "修订内容及理由" }; + tr2.getCharacterFormat().setFontSize(12f); + paragraph2.applyStyle(BuiltinStyle.Body_Text); //应用标题1样式 + + + + //定义表格数据 + String[] header = {"版本", "发布部门","拟制人","拟制日期","审核人","复核人","审批人","修订内容及理由"}; String[][] strArray2 = new String[versionHistoryTable.size()][]; - List list = (List)new LinkedList<>(); - for (int k = 0; k < versionHistoryTable.size(); k++) { - JSONObject jsonObject = versionHistoryTable.getJSONObject(k); + List list = new LinkedList<>(); + for (int i = 0; i < versionHistoryTable.size(); i++) { + JSONObject jsonObject = versionHistoryTable.getJSONObject(i); String[] strArray = new String[8]; - if (repositoryModel.getMethodId().equals("process.scheme")) { + + if(repositoryModel.getMethodId().equals("process.scheme")){ strArray[0] = jsonObject.getString("P_versions").toString(); - } else { + }else{ strArray[0] = jsonObject.getString("versions").toString(); } strArray[1] = jsonObject.getString("Issuing_department").toString(); @@ -551,314 +863,424 @@ public class OutputWordUtil { strArray[6] = jsonObject.getString("approver").toString(); strArray[7] = jsonObject.getString("Contents_and_reasons_for_revision").toString(); list.add(strArray); - strArray2[k] = strArray; + strArray2[i] = strArray; } + String[][] data = strArray2; - Table table = section1.addTable(true); + + //添加表格 + Table table = section.addTable(true); + table.getTableFormat().setHorizontalAlignment(RowAlignment.Center); + table.resetCells(data.length + 1, header.length); table.autoFit(AutoFitBehaviorType.Auto_Fit_To_Window); TableRow row = table.getRows().get(0); row.isHeader(true); row.setHeightType(TableRowHeightType.Exactly); - row.setHeight(20.0F); - table.setPreferredWidth(new PreferredWidth(WidthType.Twip, (short)8335)); - float[] columnWidths = { 10.0F, 17.0F, 13.0F, 17.0F, 13.0F, 13.0F, 13.0F, 25.0F }; - int n; - for (n = 0; n < columnWidths.length; n++) - row.getCells().get(n).setWidth(columnWidths[n]); - for (n = 0; n < header.length; n++) { - row.getCells().get(n).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle); - Paragraph p = row.getCells().get(n).addParagraph(); - TextRange txtRange = p.appendText(header[n]); + row.setHeight(20); + table.setPreferredWidth(new PreferredWidth(WidthType.Twip, (short) 8335f)); + + float[] columnWidths = {10f,17f,13f,17f,13f,13f,13f,25f}; + + // 设置列宽 + for (int i = 0; i < columnWidths.length; i++) { + row.getCells().get(i).setWidth(columnWidths[i]); + } + + + for (int i = 0; i < header.length; i++) { + row.getCells().get(i).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle); + Paragraph p = row.getCells().get(i).addParagraph(); + + TextRange txtRange = p.appendText(header[i]); + txtRange.getCharacterFormat().setBold(true); txtRange.getCharacterFormat().setFontName("宋体"); - txtRange.getCharacterFormat().setFontSize(10.5F); + txtRange.getCharacterFormat().setFontSize(10.5f); + p.getFormat().setHorizontalAlignment(HorizontalAlignment.Center); + } + + + //将数据添加到其余行 for (int r = 0; r < data.length; r++) { TableRow dataRow = table.getRows().get(r + 1); - dataRow.setHeight(20.0F); + + dataRow.setHeight(20); dataRow.setHeightType(TableRowHeightType.Auto); dataRow.getRowFormat().setBackColor(Color.white); - for (int c = 0; c < (data[r]).length; c++) { + + for (int c = 0; c < data[r].length; c++) { dataRow.getCells().get(c).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle); - TextRange text = dataRow.getCells().get(c).addParagraph().appendText(data[r][c]); + //设置固定列宽 + //dataRow.getCells().get(c).addParagraph().appendText(data[r][c]); + TextRange text =dataRow.getCells().get(c).addParagraph().appendText(data[r][c]); text.getCharacterFormat().setFontName("宋体"); - text.getCharacterFormat().setFontSize(10.5F); - for (int i1 = 0; i1 < columnWidths.length; i1++) { - row.getCells().get(i1).setWidth(columnWidths[i1]); - row.getCells().get(i1).setCellWidthType(CellWidthType.Percentage); + text.getCharacterFormat().setFontSize(10.5f); + + + // 设置列宽 + for (int i = 0; i < columnWidths.length; i++) { + row.getCells().get(i).setWidth(columnWidths[i]); + row.getCells().get(i).setCellWidthType(CellWidthType.Percentage); } + + } } - for (int m = 0; m < table.getRows().getCount(); m++) { - TableRow rows = table.getRows().get(m); - for (int i1 = 0; i1 < rows.getCells().getCount(); i1++) { - for (int z = 0; z < rows.getCells().get(i1).getParagraphs().getCount(); z++) { - Paragraph p = rows.getCells().get(i1).getParagraphs().get(z); - p.getFormat().setLineSpacing(12.0F); - if (i1 == 7 && m != 0) { - p.getFormat().setHorizontalAlignment(HorizontalAlignment.Left); - } else { - p.getFormat().setHorizontalAlignment(HorizontalAlignment.Center); + + + //遍历表格单元格 + for (int i = 0;i< table.getRows().getCount();i++) { + TableRow rows = table.getRows().get(i); + for (int j = 0; j< rows.getCells().getCount(); j++){ + for (int z= 0; z < rows.getCells().get(j).getParagraphs().getCount();z++){ + Paragraph p = rows.getCells().get(j).getParagraphs().get(z); + p.getFormat().setLineSpacing(12f);//设置边距为1.0 + if(j==7 && i !=0){ + p.getFormat().setHorizontalAlignment(Left); + }else{ + p.getFormat().setHorizontalAlignment(Center); } } } } + document.saveToFile(outFile.getPath(), FileFormat.Docx_2013); } + + + String suffix = fileName.substring(fileName.lastIndexOf(".") + 1); + if (suffix.equals("xml")) { - UtilFile utilFile1 = new UtilFile(path + fileName); - UtilFile utilFile2 = new UtilFile(docPath + fileName); + // 输出文档路径及名称 + File sourceFile = new UtilFile(path + fileName); + File targetFile = new UtilFile(docPath+ fileName); try { - UtilFile.copyFile((File)utilFile1, (File)utilFile2); + UtilFile.copyFile(sourceFile, targetFile); } catch (Exception e) { System.out.println(e); e.printStackTrace(); } - Document document1 = new Document(); - document1.loadFromFile(docPath + fileName); + + //创建实例,加载xml测试文档 + Document doc = new Document(); + doc.loadFromFile(docPath+ fileName); + + //保存为xml格式 String substring = fileName.substring(0, fileName.lastIndexOf(".xml")); - document1.saveToFile(docPath + "/xmltodoc/" + substring + ".doc", FileFormat.Doc); + //保存为Word + doc.saveToFile(docPath +"/xmltodoc/"+ substring + ".doc", FileFormat.Doc);//支持.doc + + } + + if (suffix.equals("xml")) { + //保存为xml格式 String substring = fileName.substring(0, fileName.lastIndexOf(".xml")); - document.insertTextFromFile(docPath + "/xmltodoc/" + substring + ".doc", FileFormat.Doc); + //保存为Word + document.insertTextFromFile(docPath+"/xmltodoc/" + substring + ".doc", FileFormat.Doc); + //保存结果文档 document.saveToFile(outFile.getPath(), FileFormat.Docx_2013); } else if (suffix.equals("doc") || suffix.equals("docx")) { + /*document.insertTextFromFile(path + fileName, FileFormat.Docx_2013); + //保存结果文档 + document.saveToFile(outFile.getPath(), FileFormat.Docx_2013);*/ + //此处在合并文档,着重处理此处 逻辑:大于50M走wps合并,小于50M的走jar合并 + //判断用户上传的文件的大小有多大 String fileLength = String.valueOf(dcContextpdf.length()); - String maxFileLength = SDK.getAppAPI().getProperty("com.actionsoft.apps.coe.pal", "wps_export_file_size"); - String maxFileLength_B = UtilNumber.mul(UtilNumber.mul(maxFileLength, "1024.0"), "1024"); + String maxFileLength = SDK.getAppAPI().getProperty(CoEConstant.APP_ID, "wps_export_file_size"); + String maxFileLength_B = UtilNumber.mul(UtilNumber.mul(maxFileLength, "1024.0"),"1024"); System.out.println(">>fileLength = " + fileLength); System.out.println(">>maxFileLength_B = " + maxFileLength_B); - if (Double.parseDouble(UtilNumber.sub(fileLength, maxFileLength_B)) > 0.0D) { - String appId, groupValue, fileValue, dcFileName, fileURL = outFile.getPath(); + if(Double.parseDouble(UtilNumber.sub(fileLength,maxFileLength_B))>0){//大于设置的值,则走wps逻辑 + //先获取第一个文件的下载地址 + String fileURL = outFile.getPath(); // 下载文件的URL + //..\doccenter\com.awspaas.user.apps.coe.pal.output.zd\output\11dd43d0-a3c7-4ba7-860f-6eac3383e0b0\0f4c6420-cd5d-41b6-a5b3-9c4cd5464c64\测试超级大文件_1.0.doc + //构建dc对象 System.out.println(">>>>>>>>fileURL = " + fileURL); - boolean isPrd = SDK.getAppAPI().getPropertyBooleanValue("com.actionsoft.apps.coe.pal", "isPrd", true); - if (isPrd) { - appId = fileURL.split("/")[4]; - groupValue = fileURL.split("/")[6]; - fileValue = fileURL.split("/")[7]; + //生产环境和测试环境文件路径深度不同,分别处理 + String appId;String groupValue;String fileValue;String dcFileName; + boolean isPrd = SDK.getAppAPI().getPropertyBooleanValue(CoEConstant.APP_ID, "isPrd",true); + if(isPrd){ + //生产环境和测试环境文件路径深度不同,分别处理 + appId =fileURL.split("/")[4]; + groupValue =fileURL.split("/")[6]; + fileValue =fileURL.split("/")[7]; dcFileName = fileURL.split("/")[8]; - } else { - appId = fileURL.split("/")[2]; - groupValue = fileURL.split("/")[4]; - fileValue = fileURL.split("/")[5]; + }else{ + appId =fileURL.split("/")[2]; + groupValue =fileURL.split("/")[4]; + fileValue =fileURL.split("/")[5]; dcFileName = fileURL.split("/")[6]; } String dcReposirotyName = "output"; - System.out.println("dc = " + appId + "|" + groupValue + "|" + fileValue + "|" + dcFileName); - DCPluginProfile dcPluginProfile = SDK.getDCAPI().getDCProfile(appId, dcReposirotyName); - DCContext dc = new DCContext(userContext, dcPluginProfile, "com.awspaas.user.apps.coe.pal.output.zd", groupValue, fileValue, dcFileName); + System.out.println("dc = " + appId + "|"+groupValue+"|"+fileValue+"|"+dcFileName); + DCPluginProfile dcPluginProfile =SDK.getDCAPI().getDCProfile(appId,dcReposirotyName); + DCContext dc =new DCContext(userContext,dcPluginProfile,"com.awspaas.user.apps.coe.pal.output.zd",groupValue,fileValue,dcFileName); System.out.println("dc.getDownloadURL() = " + dc.getDownloadURL()); - mergeFileForWPS(dc, dc.getDownloadURL(), dcFileName, dcContextpdf.getDownloadURL(), fileName); - } else { + //修改成调用wps文件发送 + mergeFileForWPS(dc,dc.getDownloadURL(), dcFileName,dcContextpdf.getDownloadURL(),fileName); + }else{//小于设定的值,则走第三方类库逻辑 Document docs1 = new Document(); docs1.loadFromFile(outFile.getPath()); + // 加载文档2 Document docs2 = new Document(); docs2.loadFromFile(path + fileName); SectionCollection sections2 = docs2.getSections(); - sections2.insert(0, (IDocumentObject)docs1.getSections().get(1).deepClone()); - sections2.insert(0, (IDocumentObject)docs1.getSections().get(0).deepClone()); + sections2.insert(0, docs1.getSections().get(1).deepClone()); + sections2.insert(0, docs1.getSections().get(0).deepClone()); + // 保存文档2 docs2.saveToFile(outFile.getPath(), FileFormat.Docx_2013); docs2.dispose(); } } else if (suffix.equals("pptx")) { isPPT = true; } - if (!isPPT) + if (isPPT == false) { + + //复制页眉页脚操作 try { + //加载纵向模板文档用于复制 Document doc1 = new Document(); doc1.loadFromFile(tempPath + "制度-手册5.doc"); + + //获取section Section section1 = doc1.getSections().get(0); + + //加载文档2 Document doc2 = new Document(); doc2.loadFromFile(outFile.getPath()); SectionCollection sections = doc2.getSections(); + + + //加载文档1 Document doc3 = new Document(); doc3.loadFromFile(tempPath + "横板页眉页脚模板.doc"); + // 将页眉复制到目标文档的第三节以及后续节 + for (int i = 2; i < doc2.getSections().getCount(); i++) { + Section targetSection = doc2.getSections().get(i); - - for (int k = 2; k < doc2.getSections().getCount(); k++) { - Section targetSection = doc2.getSections().get(k); - - - double width = targetSection.getPageSetup().getPageSize().getWidth(); - double height = targetSection.getPageSetup().getPageSize().getHeight(); - - // 实际方向(根据尺寸) - boolean actualLandscape = isLandscapeBySize(width, height); - - Document templateDoc = actualLandscape ? doc3 : doc1; - - HeaderFooter sourceHeader = templateDoc.getSections().get(0).getHeadersFooters().getHeader(); - - HeaderFooter targetHeader = targetSection.getHeadersFooters().getHeader(); - targetHeader.getChildObjects().clear(); - - - - HeaderFooter header = targetSection.getHeadersFooters().getHeader(); - Paragraph hpara= header.addParagraph(); - - // 先添加文字到页眉左侧 - TextRange txt = hpara.appendText(dataMap.getString("HEADERFONT")); - txt.getCharacterFormat().setUnderlineStyle(UnderlineStyle.None); - txt.getCharacterFormat().setFontSize(10f); - txt.getCharacterFormat().setFontName("黑体"); - - - - // 添加制表符以实现右侧定位 - hpara.appendText("\t"); - - // 添加图片到页眉右侧 - DocPicture pic = hpara.appendPicture(dataMap.getString("LOGOURL")); - pic.setHorizontalAlignment(ShapeHorizontalAlignment.Right); - pic.setVerticalOrigin(VerticalOrigin.Top_Margin_Area); - pic.setVerticalAlignment(ShapeVerticalAlignment.Center); - pic.setWidth(44.0F); - pic.setHeight(35.0F); - // 设置段落格式:左侧文字左对齐,右侧图片右对齐 - hpara.getFormat().setHorizontalAlignment(HorizontalAlignment.Left); - hpara.getFormat().setLeftIndent(0f); - hpara.getFormat().setFirstLineIndent(0f); - - hpara.getFormat().setAfterSpacing(25f); // 增加段后间距,可以根据需要调整数值 - hpara.getFormat().setBeforeSpacing(25f); // 也可以调整段前间距 - - - // 设置制表位以实现右侧定位 - Tab tab = hpara.getFormat().getTabs().addTab(500f, TabJustification.Right, TabLeader.No_Leader); - - - // 设置图片的文本环绕方式 - pic.setTextWrappingStyle(TextWrappingStyle.Behind); - - // 设置页眉底部边线(粗细、间距)- 文字和图片都在横线上面 - hpara.getFormat().getBorders().getBottom().setBorderType(BorderStyle.Single); - hpara.getFormat().getBorders().getBottom().setLineWidth(0.5f); - hpara.getFormat().getBorders().setSpace(1f); - - - - - /*for(int c = 0; c < targetHeader.getChildObjects().getCount(); ++c) { - DocumentObject childObj = targetHeader.getChildObjects().get(c); - - if (childObj instanceof Table) { - Table table = (Table) childObj; - - if (table.getRows().getCount() > 0 && table.getRows().get(0).getCells().getCount() > 0) { - // 处理左侧单元格的文字 - TableCell cell = table.getRows().get(0).getCells().get(0); - if (cell.getParagraphs().getCount() > 0) { - String originalText = cell.getParagraphs().get(0).getText(); - System.out.println("HEADERFONT = " + originalText); - cell.getParagraphs().get(0).setText(dataMap.getString("HEADERFONT")); - } - - // 处理右侧单元格的图片 - if (table.getRows().get(0).getCells().getCount() > 1) { - TableCell cellImg = table.getRows().get(0).getCells().get(1); - processImageCell(cellImg, dataMap.getString("LOGOURL")); - } - } - }else if(childObj instanceof Paragraph){ - processParagraph((Paragraph)childObj, dataMap); - - } - }*/ - - - } - - - - - - - - - - for (int k = 2; k < doc2.getSections().getCount(); k++) { - Section targetSection = doc2.getSections().get(k); - HeaderFooter targetFooter = targetSection.getHeadersFooters().getFooter(); PageSetup pageSetup = targetSection.getPageSetup(); + PageOrientation orientation = pageSetup.getOrientation(); + + + // 根据合并文档节的页面方向选择模板 PageOrientation mergeOrientation = pageSetup.getOrientation(); + Document templateDoc = (mergeOrientation == PageOrientation.Landscape) ? doc3 : doc1; - double width = targetSection.getPageSetup().getPageSize().getWidth(); - double height = targetSection.getPageSetup().getPageSize().getHeight(); + // 复制模板文档的页眉和页脚到新文档 + HeaderFooter sourceHeader = templateDoc.getSections().get(0).getHeadersFooters().getHeader(); - // 实际方向(根据尺寸) - boolean actualLandscape = isLandscapeBySize(width, height); + HeaderFooter targetHeader = targetSection.getHeadersFooters().getHeader(); + targetHeader.getChildObjects().clear(); - Document templateDoc = actualLandscape ? doc3 : doc1; + for (int j = 0; j < sourceHeader.getChildObjects().getCount(); j++) { + //定制页眉 + Table table = (Table)sourceHeader.getChildObjects().get(0); + if (table.getRows().getCount() > 0 && table.getRows().get(0).getCells().getCount() > 0) { + //页眉文字 + TableCell cell = table.getRows().get(0).getCells().get(0); + String text = cell.getParagraphs().get(0).getText();// 假设单元格中只有一个TextRange + cell.getParagraphs().get(0).setText(dataMap.getString("HEADERFONT")); + //页眉logo + String logoUrl = dataMap.getString("LOGOURL"); + TableCell cellImg = table.getRows().get(0).getCells().get(1); + IParagraph firstParagraph = cellImg.getFirstParagraph(); + //进行替换 + firstParagraph.getChildObjects().removeAt(0); + DocPicture picture = firstParagraph.appendPicture(logoUrl); + picture.setWidth(44); + picture.setHeight(35); + } + DocumentObject obj = sourceHeader.getChildObjects().get(j).deepClone(); + targetHeader.getChildObjects().add(obj); + } + } + // 将页脚复制到目标文档的第三节以及后续节 + for (int i = 2; i < doc2.getSections().getCount(); i++) { + Section targetSection = doc2.getSections().get(i); + HeaderFooter targetFooter = targetSection.getHeadersFooters().getFooter(); + + PageSetup pageSetup = targetSection.getPageSetup(); + + PageOrientation mergeOrientation = pageSetup.getOrientation(); + Document templateDoc = (mergeOrientation == PageOrientation.Landscape) ? doc3 : doc1; + HeaderFooter sourceFooter = templateDoc.getSections().get(0).getHeadersFooters().getFooter(); - HeaderFooter sourceFooter = templateDoc.getSections().get(0).getHeadersFooters().getFooter(); targetFooter.getChildObjects().clear(); - - /* for (int m = 0; m < sourceFooter.getChildObjects().getCount(); m++) { + for (int j = 0; j < sourceFooter.getChildObjects().getCount(); j++) { + //定制页脚 Table table = (Table)sourceFooter.getChildObjects().get(1); if (table.getRows().getCount() > 0 && table.getRows().get(0).getCells().getCount() > 0) { + // 定位到第一行第一列的单元格 TableCell cell = table.getRows().get(0).getCells().get(0); - String text = cell.getParagraphs().get(0).getText(); - - cell.getParagraphs().get(0).setText(dataMap.getString("FOOTERFONT")); + // 修改单元格中的文本 + String text = cell.getParagraphs().get(0).getText();// 假设单元格中只有一个TextRange + cell.getParagraphs().get(0).setText(dataMap.getString("FOOTERFONT")); } - DocumentObject obj = sourceFooter.getChildObjects().get(m).deepClone(); - targetFooter.getChildObjects().add((IDocumentObject)obj); - }*/ - - HeaderFooter header = targetSection.getHeadersFooters().getFooter(); - Paragraph fpara= header.addParagraph(); - // 先添加文字到页脚左侧 - TextRange txt = fpara.appendText(dataMap.getString("FOOTERFONT")); - txt.getCharacterFormat().setUnderlineStyle(UnderlineStyle.None); - txt.getCharacterFormat().setFontSize(10f); - txt.getCharacterFormat().setFontName("黑体"); - - - fpara.getFormat().getBorders().getTop().setBorderType(BorderStyle.Single); - fpara.getFormat().getBorders().getTop().setLineWidth(1f); - - - // 设置页脚文字左对齐 - fpara.getFormat().setHorizontalAlignment(HorizontalAlignment.Left); - - // 调整页脚段落的间距,确保横线在文字上方有适当距离 - fpara.getFormat().setBeforeSpacing(15f); // 增加段前间距,让横线与文字之间有足够空间 - fpara.getFormat().setAfterSpacing(5f); // 段后间距 - - - + DocumentObject obj = sourceFooter.getChildObjects().get(j).deepClone(); + targetFooter.getChildObjects().add(obj); + } } + + + + + doc2.saveToFile(outFile.getPath(), FileFormat.Docx_2013); + } catch (Exception e) { e.printStackTrace(); } finally { - if (document != null) + // 关闭文档对象 + if (document != null) { document.close(); + } } + } + } } + + + long b2 = System.currentTimeMillis(); - System.err.println("复制附件用时:" + ((b2 - b1) / 1000L) + "秒"); + + System.err.println("复制附件用时:" + + (b2 - b1) / 1000 + "秒"); } + + + /****************************插入支持文件、相关文件、附则等信息********************************************************/ + + Document doc = new Document(outFile.getPath()); + //获取最后一节 Section section = doc.getLastSection(); - JSONArray riskMatrix = new JSONArray(); + + //添加段落,设置一级序列 + //Paragraph paragraph = section.addParagraph(); + + //paragraph.appendBreak(BreakType.Page_Break); + + // 开始 + /*********************************************************关键控制点风险矩阵 begin**********************************************************************************/ + /* PALRepositoryPropertyModel riskMatrixInfo = PALRepositoryPropertyCache.getPropertyByPropertyId(repositoryModel.getId(), "riskMatrixInfo"); + if(null!=riskMatrixInfo){ + JSONObject jsonObject = JSONObject.parseObject(riskMatrixInfo.getPropertyValue()); + if(null != jsonObject){ + JSONArray tableInfo = jsonObject.getJSONArray("table"); + //看看tableInfo是什么内容,如果没有内容,也不用生成表格 + System.out.println(">>>>>>>>>tableInfo.toString() = " + tableInfo.toString()); + if(tableInfo.size()>1){ + + CharacterFormat format2 = new CharacterFormat(); + //创建字体格式 + format2.setFontName("宋体"); + //添加段落,设置一级序列 + Paragraph paragraph2 = section.addParagraph(); + ParagraphFormat paragraphFormat2 = paragraph2.getFormat(); + paragraphFormat2.setHorizontalAlignment(Left); + TextRange tr2 = paragraph2.appendText("关键控制点风险矩阵"); + tr2.getCharacterFormat().setBold(true); + tr2.getCharacterFormat().setFontName("宋体"); + tr2.getCharacterFormat().setFontSize(12f); + paragraph2.applyStyle(BuiltinStyle.Body_Text); //应用标题1样式 + + + + //定义表格数据 + String[] header = {"关键控制点", "控制描述","对应风险描述","角色/岗位"}; + //添加表格的表头 + Table table = section.addTable(true); + table.resetCells(tableInfo.size(),header.length); + //table.getTableFormat().isAutoResized(true); + table.autoFit(AutoFitBehaviorType.Auto_Fit_To_Window); + TableRow row = table.getRows().get(0); + row.isHeader(true); + row.setHeightType(TableRowHeightType.Auto); + for (int i = 0; i < header.length; i++) { + row.getCells().get(i).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle); + Paragraph p = row.getCells().get(i).addParagraph(); + p.getFormat().setHorizontalAlignment(Center); + TextRange txtRange = p.appendText(header[i]); + txtRange.getCharacterFormat().setBold(true); + txtRange.getCharacterFormat().setFontName("宋体"); + txtRange.getCharacterFormat().setFontSize(10.5f); + } + + + //添加数据到表中 + for (int i = 1; i < tableInfo.size(); i++) { + JSONObject cellInfo = tableInfo.getJSONObject(i); + TableRow dataRow = table.getRows().get(i); + dataRow.setHeight(25); + dataRow.setHeightType(TableRowHeightType.Exactly); + int flagNum = 0; + for (String cellKey : cellInfo.keySet()) { + if(cellKey.equals("id")){ + continue; + } + dataRow.getCells().get(flagNum).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle); + + TableCell cell = dataRow.getCells().get(flagNum); + + + // 清除单元格原有段落(重要!) + cell.getParagraphs().clear(); + + Paragraph p = cell.addParagraph(); + + + // 第一列居中,第二列居左 + if (flagNum == 0) { + p.getFormat().setHorizontalAlignment(HorizontalAlignment.Center); + } else { + p.getFormat().setHorizontalAlignment(HorizontalAlignment.Left); + + } + + TextRange text =dataRow.getCells().get(flagNum).addParagraph().appendText(cellInfo.getString(cellKey)); + text.getCharacterFormat().setFontName("宋体"); + text.getCharacterFormat().setFontSize(10.5f); + flagNum++; + + } + + } + + + Paragraph paragraph_blank = section.addParagraph(); + } + } + }*/ + + + + + + JSONArray riskMatrix = new JSONArray(); //组织职责Table PALRepositoryPropertyModel riskMatrixInfoData = PALRepositoryPropertyCache.getPropertyByPropertyId(repositoryModel.getId(), "riskMatrixInfo"); - if (null != riskMatrixInfoData) { + + + if(null!=riskMatrixInfoData) { JSONObject jsonObject = JSONObject.parseObject(riskMatrixInfoData.getPropertyValue()); if (null != jsonObject) { JSONArray tableInfo = jsonObject.getJSONArray("table"); + //看看tableInfo是什么内容,如果没有内容,也不用生成表格 System.out.println(">>>>>>>>>tableInfo.toString() = " + tableInfo.toString()); if (tableInfo.size() > 1) { - int j = 0; + + int index = 0; + + //添加数据到表中 for (int i = 1; i < tableInfo.size(); i++) { JSONObject cellInfo = tableInfo.getJSONObject(i); JSONObject tmp = new JSONObject(); @@ -869,108 +1291,163 @@ public class OutputWordUtil { riskMatrix.add(tmp); } CharacterFormat format2 = new CharacterFormat(); + //创建字体格式 format2.setFontName("宋体"); + //添加段落,设置一级序列 Paragraph paragraph2 = section.addParagraph(); ParagraphFormat paragraphFormat2 = paragraph2.getFormat(); - paragraphFormat2.setHorizontalAlignment(HorizontalAlignment.Left); + paragraphFormat2.setHorizontalAlignment(Left); TextRange tr2 = paragraph2.appendText("关键控制点风险矩阵"); tr2.getCharacterFormat().setBold(true); tr2.getCharacterFormat().setFontName("宋体"); - tr2.getCharacterFormat().setFontSize(12.0F); - paragraph2.applyStyle(BuiltinStyle.Body_Text); - String[] header = { "关键控制点", "控制描述", "对应风险描述", "角色/岗位" }; + tr2.getCharacterFormat().setFontSize(12f); + paragraph2.applyStyle(BuiltinStyle.Body_Text); //应用标题1样式 + + + //定义表格数据 + String[] header = {"关键控制点", "控制描述","对应风险描述","角色/岗位"}; String[][] strArray2 = new String[riskMatrix.size()][]; - List list = (List)new LinkedList<>(); - for (int k = 0; k < riskMatrix.size(); k++) { - JSONObject jsonObject1 = riskMatrix.getJSONObject(k); + List list = new LinkedList<>(); + for (int i = 0; i < riskMatrix.size(); i++) { + JSONObject jsonObject1 = riskMatrix.getJSONObject(i); String[] strArray = new String[4]; strArray[0] = jsonObject1.getString("firstColumn").toString(); strArray[1] = jsonObject1.getString("secondColumn").toString(); strArray[2] = jsonObject1.getString("threeColumn").toString(); strArray[3] = jsonObject1.getString("fourColumn").toString(); list.add(strArray); - strArray2[k] = strArray; + strArray2[i] = strArray; } + String[][] data = strArray2; + + //添加表格 Table table = section.addTable(true); table.resetCells(data.length + 1, header.length); + table.autoFit(AutoFitBehaviorType.Auto_Fit_To_Window); + + TableRow row = table.getRows().get(0); row.isHeader(true); - row.setHeight(20.0F); + row.setHeight(20); row.setHeightType(TableRowHeightType.Exactly); - for (int m = 0; m < header.length; m++) { - row.getCells().get(m).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle); - Paragraph p = row.getCells().get(m).addParagraph(); - p.getFormat().setHorizontalAlignment(HorizontalAlignment.Center); - TextRange txtRange = p.appendText(header[m]); + for (int i = 0; i < header.length; i++) { + row.getCells().get(i).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle); + Paragraph p = row.getCells().get(i).addParagraph(); + p.getFormat().setHorizontalAlignment(Center); + TextRange txtRange = p.appendText(header[i]); txtRange.getCharacterFormat().setBold(true); txtRange.getCharacterFormat().setFontName("宋体"); - txtRange.getCharacterFormat().setFontSize(10.5F); + txtRange.getCharacterFormat().setFontSize(10.5f); } - float[] columnWidths = { 20.0F, 30.0F, 30.0F, 20.0F }; - for (int n = 0; n < columnWidths.length; n++) - row.getCells().get(n).setWidth(columnWidths[n]); + + + float[] columnWidths = {20f, 30f,30f,20f}; // 比例总和为100% + + // 设置列宽 + for (int i = 0; i < columnWidths.length; i++) { + row.getCells().get(i).setWidth(columnWidths[i]); + } + + //将数据添加到其余行 for (int r = 0; r < data.length; r++) { TableRow dataRow = table.getRows().get(r + 1); - dataRow.setHeight(20.0F); + dataRow.setHeight(20); + //dataRow.setHeightType(TableRowHeightType.Auto); dataRow.getRowFormat().setBackColor(Color.white); - for (int c = 0; c < (data[r]).length; c++) { + for (int c = 0; c < data[r].length; c++) { + TableCell cell = dataRow.getCells().get(c); + dataRow.getCells().get(c).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle); + + // 清除单元格原有段落(重要!) cell.getParagraphs().clear(); + Paragraph p = cell.addParagraph(); + + + // 第一列居中,第二列居左 if (c == 0) { p.getFormat().setHorizontalAlignment(HorizontalAlignment.Center); } else { p.getFormat().setHorizontalAlignment(HorizontalAlignment.Left); + } TextRange text = p.appendText(data[r][c]); text.getCharacterFormat().setFontName("宋体"); - text.getCharacterFormat().setFontSize(10.5F); - for (int i1 = 0; i1 < columnWidths.length; i1++) { - dataRow.getCells().get(i1).setWidth(columnWidths[i1]); - dataRow.getCells().get(i1).setCellWidthType(CellWidthType.Percentage); + text.getCharacterFormat().setFontSize(10.5f); + + // 设置列宽 + for (int i = 0; i < columnWidths.length; i++) { + dataRow.getCells().get(i).setWidth(columnWidths[i]); + dataRow.getCells().get(i).setCellWidthType(CellWidthType.Percentage); + } } } - Paragraph paragraph1 = section.addParagraph(); + + + Paragraph paragraph_blank = section.addParagraph(); + + } + + + } } - } - JSONArray related_support_files = new JSONArray(); + + + + + /*********************************************************关键控制点风险矩阵 end******************************************************************/ + + + + /**********************************************相关/支持文件表格绘制 begin**********************************************************************/ + JSONArray related_support_files = new JSONArray(); //组织职责Table List relationList = DesignerShapeRelationCache.getListByAttrId(repositoryModel.getId(), "", "related_support_files"); + relationList.sort(Comparator.comparing(DesignerShapeRelationModel::getShapeText)); + int index = 0; if (relationList.size() > 0) { for (DesignerShapeRelationModel relation : relationList) { - String relationFileId = relation.getRelationFileId(); + String relationFileId = relation.getRelationFileId();// 支持或相关文件的ID List models = PALRepositoryCache.getByVersionId(relationFileId); if (models != null && models.size() > 0) { index++; - for (PALRepositoryModel oneModel : models) { - if (oneModel.isUse() == true) { + for(PALRepositoryModel oneModel:models){ + if(oneModel.isUse()==true){ JSONObject tmp = new JSONObject(); tmp.put("name", oneModel.getName()); - tmp.put("desc", Integer.valueOf(index)); + tmp.put("desc", index); related_support_files.add(tmp); } } } } + + CharacterFormat format2 = new CharacterFormat(); + //创建字体格式 format2.setFontName("宋体"); + //添加段落,设置一级序列 Paragraph paragraph2 = section.addParagraph(); ParagraphFormat paragraphFormat2 = paragraph2.getFormat(); - paragraphFormat2.setHorizontalAlignment(HorizontalAlignment.Left); + paragraphFormat2.setHorizontalAlignment(Left); TextRange tr2 = paragraph2.appendText("相关/支持文件"); tr2.getCharacterFormat().setBold(true); tr2.getCharacterFormat().setFontName("宋体"); - tr2.getCharacterFormat().setFontSize(12.0F); - paragraph2.applyStyle(BuiltinStyle.Body_Text); - String[] header = { "序号", "文件名称" }; + tr2.getCharacterFormat().setFontSize(12f); + paragraph2.applyStyle(BuiltinStyle.Body_Text); //应用标题1样式 + + + //定义表格数据 + String[] header = {"序号", "文件名称"}; String[][] strArray2 = new String[related_support_files.size()][]; - List list = (List)new LinkedList<>(); + List list = new LinkedList<>(); for (int i = 0; i < related_support_files.size(); i++) { JSONObject jsonObject = related_support_files.getJSONObject(i); String[] strArray = new String[2]; @@ -979,96 +1456,149 @@ public class OutputWordUtil { list.add(strArray); strArray2[i] = strArray; } + String[][] data = strArray2; + + //添加表格 Table table = section.addTable(true); table.resetCells(data.length + 1, header.length); + table.autoFit(AutoFitBehaviorType.Auto_Fit_To_Window); + + TableRow row = table.getRows().get(0); row.isHeader(true); - row.setHeight(20.0F); + row.setHeight(20); row.setHeightType(TableRowHeightType.Exactly); - for (int j = 0; j < header.length; j++) { - row.getCells().get(j).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle); - Paragraph p = row.getCells().get(j).addParagraph(); - p.getFormat().setHorizontalAlignment(HorizontalAlignment.Center); - TextRange txtRange = p.appendText(header[j]); + for (int i = 0; i < header.length; i++) { + row.getCells().get(i).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle); + Paragraph p = row.getCells().get(i).addParagraph(); + p.getFormat().setHorizontalAlignment(Center); + TextRange txtRange = p.appendText(header[i]); txtRange.getCharacterFormat().setBold(true); txtRange.getCharacterFormat().setFontName("宋体"); - txtRange.getCharacterFormat().setFontSize(10.5F); + txtRange.getCharacterFormat().setFontSize(10.5f); } - float[] columnWidths = { 10.0F, 90.0F }; - for (int k = 0; k < columnWidths.length; k++) { - row.getCells().get(k).setWidth(columnWidths[k]); - row.getCells().get(k).setCellWidthType(CellWidthType.Percentage); + + float[] columnWidths = {10f, 90f}; // 比例总和为100% + + // 设置列宽 + for (int i = 0; i < columnWidths.length; i++) { + row.getCells().get(i).setWidth(columnWidths[i]); + row.getCells().get(i).setCellWidthType(CellWidthType.Percentage); + } + + + //将数据添加到其余行 for (int r = 0; r < data.length; r++) { TableRow dataRow = table.getRows().get(r + 1); - dataRow.setHeight(20.0F); + dataRow.setHeight(20); + //dataRow.setHeightType(TableRowHeightType.Auto); dataRow.getRowFormat().setBackColor(Color.white); - for (int c = 0; c < (data[r]).length; c++) { + for (int c = 0; c < data[r].length; c++) { + TableCell cell = dataRow.getCells().get(c); + dataRow.getCells().get(c).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle); + + // 清除单元格原有段落(重要!) cell.getParagraphs().clear(); + Paragraph p = cell.addParagraph(); + + + // 第一列居中,第二列居左 if (c == 0) { p.getFormat().setHorizontalAlignment(HorizontalAlignment.Center); } else { p.getFormat().setHorizontalAlignment(HorizontalAlignment.Left); + } TextRange text = p.appendText(data[r][c]); text.getCharacterFormat().setFontName("宋体"); - text.getCharacterFormat().setFontSize(10.5F); - for (int m = 0; m < columnWidths.length; m++) { - dataRow.getCells().get(m).setWidth(columnWidths[m]); - dataRow.getCells().get(m).setCellWidthType(CellWidthType.Percentage); + text.getCharacterFormat().setFontSize(10.5f); + + // 设置列宽 + for (int i = 0; i < columnWidths.length; i++) { + dataRow.getCells().get(i).setWidth(columnWidths[i]); + dataRow.getCells().get(i).setCellWidthType(CellWidthType.Percentage); + } } } - Paragraph paragraph1 = section.addParagraph(); + + + + Paragraph paragraph_blank = section.addParagraph(); } + + /**********************************************相关/支持文件表格绘制 end*********************************************************************/ + + + + + /**********************************************外部相关文件表格绘制 begin*********************************************************************/ + int extercount = 0; - JSONArray ExternalCorrelationFileArray = new JSONArray(); - String sqlOut = "select PROPERTYVALUE from APP_ACT_COE_PAL_PROP where PLID = '" + repositoryModel.getId() + "' and PROPERTYID = 'Out_related_files'"; + //外部相关文件 + JSONArray ExternalCorrelationFileArray = new JSONArray(); //外部相关文件Table + String sqlOut = "select PROPERTYVALUE from APP_ACT_COE_PAL_PROP where PLID = '"+repositoryModel.getId()+"' and PROPERTYID = 'Out_related_files'"; String outRelatFileJson = DBSql.getString(sqlOut); - if (UtilString.isNotEmpty(outRelatFileJson)) { - if (outRelatFileJson.contains(",")) { + if(UtilString.isNotEmpty(outRelatFileJson)) { + if(outRelatFileJson.contains(",")) { String[] split = outRelatFileJson.split(","); for (String str : split) { extercount++; JSONObject tmp = new JSONObject(); - tmp.put("name", str + "【外部】"); - tmp.put("desc", Integer.valueOf(extercount)); + tmp.put("name", str+"【外部】"); + tmp.put("desc", extercount); ExternalCorrelationFileArray.add(tmp); } - } else if (outRelatFileJson.contains(",")) { + }else if(outRelatFileJson.contains(",")) { String[] split = outRelatFileJson.split(","); for (String str : split) { extercount++; JSONObject tmp = new JSONObject(); - tmp.put("name", str + "【外部】"); - tmp.put("desc", Integer.valueOf(extercount)); + tmp.put("name", str+"【外部】"); + tmp.put("desc", extercount); ExternalCorrelationFileArray.add(tmp); } - } else { + }else { extercount++; JSONObject tmp = new JSONObject(); - tmp.put("name", outRelatFileJson + "【外部】"); - tmp.put("desc", Integer.valueOf(extercount)); + tmp.put("name", outRelatFileJson+"【外部】"); + tmp.put("desc", extercount); ExternalCorrelationFileArray.add(tmp); } + + + CharacterFormat format = new CharacterFormat(); + //创建字体格式 format.setFontName("宋体"); + //添加段落,设置一级序列 Paragraph paragraph1 = section.addParagraph(); + ParagraphFormat paragraphFormat1 = paragraph1.getFormat(); - paragraphFormat1.setHorizontalAlignment(HorizontalAlignment.Left); + paragraphFormat1.setHorizontalAlignment(Left); + TextRange tr = paragraph1.appendText("外部相关文件"); tr.getCharacterFormat().setBold(true); tr.getCharacterFormat().setFontName("宋体"); - tr.getCharacterFormat().setFontSize(12.0F); - paragraph1.applyStyle(BuiltinStyle.Body_Text); - String[] header = { "序号", "文件名称" }; + tr.getCharacterFormat().setFontSize(12f); + //tr.applyCharacterFormat(format); //应用字体格式 + paragraph1.applyStyle(BuiltinStyle.Body_Text); //应用标题1样式 + + + + + + //定义表格数据 + String[] header = {"序号", "文件名称"}; + String[][] strArray2 = new String[ExternalCorrelationFileArray.size()][]; - List list = (List)new LinkedList<>(); + List list = new LinkedList<>(); for (int i = 0; i < ExternalCorrelationFileArray.size(); i++) { JSONObject jsonObject = ExternalCorrelationFileArray.getJSONObject(i); String[] strArray = new String[2]; @@ -1077,333 +1607,248 @@ public class OutputWordUtil { list.add(strArray); strArray2[i] = strArray; } + String[][] data = strArray2; + + //添加表格 Table table = section.addTable(true); table.resetCells(data.length + 1, header.length); table.autoFit(AutoFitBehaviorType.Auto_Fit_To_Window); TableRow row = table.getRows().get(0); row.isHeader(true); - row.setHeight(20.0F); + row.setHeight(20); row.setHeightType(TableRowHeightType.Exactly); - for (int j = 0; j < header.length; j++) { - TableCell cell = row.getCells().get(j); - row.getCells().get(j).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle); + + + + for (int i = 0; i < header.length; i++) { + + TableCell cell = row.getCells().get(i); + + row.getCells().get(i).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle); + + // 清除单元格原有段落(重要!) cell.getParagraphs().clear(); - Paragraph p = row.getCells().get(j).addParagraph(); + + Paragraph p = row.getCells().get(i).addParagraph(); p.getFormat().setHorizontalAlignment(HorizontalAlignment.Center); - TextRange txtRange = p.appendText(header[j]); + + TextRange txtRange = p.appendText(header[i]); txtRange.getCharacterFormat().setBold(true); txtRange.getCharacterFormat().setFontName("宋体"); - txtRange.getCharacterFormat().setFontSize(10.5F); + txtRange.getCharacterFormat().setFontSize(10.5f); + } - float[] columnWidths = { 10.0F, 90.0F }; + + + float[] columnWidths = {10f, 90f}; // 比例总和为100% + + + //将数据添加到其余行 for (int r = 0; r < data.length; r++) { TableRow dataRow = table.getRows().get(r + 1); - dataRow.setHeight(20.0F); - for (int c = 0; c < (data[r]).length; c++) { + dataRow.setHeight(20); + //dataRow.setHeightType(TableRowHeightType.Exactly); + for (int c = 0; c < data[r].length; c++) { TableCell cell = dataRow.getCells().get(c); + dataRow.getCells().get(c).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle); + + // 清除单元格原有段落(重要!) cell.getParagraphs().clear(); + Paragraph p = cell.addParagraph(); + + + // 第一列居中,第二列居左 if (c == 0) { p.getFormat().setHorizontalAlignment(HorizontalAlignment.Center); } else { p.getFormat().setHorizontalAlignment(HorizontalAlignment.Left); + } TextRange text = p.appendText(data[r][c]); text.getCharacterFormat().setFontName("宋体"); - text.getCharacterFormat().setFontSize(10.5F); - for (int k = 0; k < columnWidths.length; k++) { - row.getCells().get(k).setWidth(columnWidths[k]); - row.getCells().get(k).setCellWidthType(CellWidthType.Percentage); + text.getCharacterFormat().setFontSize(10.5f); + + // 设置列宽 + for (int i = 0; i < columnWidths.length; i++) { + row.getCells().get(i).setWidth(columnWidths[i]); + row.getCells().get(i).setCellWidthType(CellWidthType.Percentage); + } } } - Paragraph paragraph2 = section.addParagraph(); + + + + + + + + Paragraph paragraph_blank = section.addParagraph(); } + + /**********************************************外部相关文件表格绘制 end*********************************************************************/ + + + + + //查询模型文件属性上传附件信息 List search2 = upFileDao.searchByRepositoryId(repositoryModel.getId(), "f"); + DCContext dcContextModel = null; + //读取模型附件插入手册中文档对象 if (search2 != null && search2.size() > 0) { + //插入前,附件名先排序先排序 sortFilesByNumber(search2); + //附件如果为空,不插入附件标题 CharacterFormat format4 = new CharacterFormat(); + //创建字体格式 format4.setFontName("宋体"); + //添加段落 Paragraph paragraph4 = section.addParagraph(); + ParagraphFormat paragraphFormat4 = paragraph4.getFormat(); - paragraphFormat4.setHorizontalAlignment(HorizontalAlignment.Left); + paragraphFormat4.setHorizontalAlignment(Left); + TextRange tr4 = paragraph4.appendText("附件"); + + tr4.getCharacterFormat().setBold(true); tr4.getCharacterFormat().setFontName("宋体"); - tr4.getCharacterFormat().setFontSize(12.0F); - paragraph4.applyStyle(BuiltinStyle.Body_Text); + tr4.getCharacterFormat().setFontSize(12); + paragraph4.applyStyle(BuiltinStyle.Body_Text); //应用标题1样式 + + long b1 = System.currentTimeMillis(); + for (UpfileModel upfileModel : search2) { - DCPluginProfile dcProfile = DCProfileManager.getDCProfile("com.actionsoft.apps.coe.pal", "COE_Upfile"); + DCPluginProfile dcProfile = DCProfileManager.getDCProfile(CoEConstant.APP_ID, CoeFileConstant.COE_UPFILE); if (dcProfile != null) { - dcContextModel = new DCContext(userContext, dcProfile, "com.actionsoft.apps.coe.pal", "file", upfileModel.getPl_uuid(), upfileModel.getFileName()); + + // 处理DocCenter + dcContextModel = new DCContext(userContext, dcProfile, CoEConstant.APP_ID, "file", upfileModel.getPl_uuid(), upfileModel.getFileName()); + //添加段落 Paragraph paragraph5 = section.addParagraph(); + //加载一个图片,它将作为外部文件的符号显示在Word文档中 + //获取最后一个.的位置 int lastIndexOf = dcContextModel.getFileName().lastIndexOf("."); + //获取文件的后缀名 .jpg String suffix = dcContextModel.getFileName().substring(lastIndexOf); - DocPicture pdfIcon = new DocPicture((IDocument)doc); + + DocPicture pdfIcon = new DocPicture(doc); + InputStream stream1 = new FileInputStream(dcContextModel.getFilePath()); - DocPicture pic1 = new DocPicture((IDocument)doc); + DocPicture pic1 = new DocPicture(doc); + if (suffix.equals(".doc") || suffix.equals(".docx")) { pic1.loadImage("../doccenter/com.awspaas.user.apps.coe.pal.output.zd/filepic/word.png"); - paragraph5.appendText(dcContextModel.getFileName() + " "); - paragraph5.applyStyle(BuiltinStyle.Body_Text); + paragraph5.appendText(dcContextModel.getFileName()+" "); + paragraph5.applyStyle(BuiltinStyle.Body_Text); //应用标题1样式 if (suffix.equals(".doc")) { paragraph5.appendOleObject(stream1, pic1, "doc"); - continue; - } - if (suffix.equals(".docx")) + } else if (suffix.equals(".docx")) { paragraph5.appendOleObject(stream1, pic1, "docx"); - continue; - } - if (suffix.equals(".pdf")) { + } + } else if (suffix.equals(".pdf")) { pic1.loadImage("../doccenter/com.awspaas.user.apps.coe.pal.output.zd/filepic/pdf.png"); - paragraph5.appendText(dcContextModel.getFileName() + " "); - paragraph5.applyStyle(BuiltinStyle.Body_Text); + paragraph5.appendText(dcContextModel.getFileName()+" "); + paragraph5.applyStyle(BuiltinStyle.Body_Text); //应用标题1样式 paragraph5.appendOleObject(stream1, pic1, "pdf"); - continue; - } - if (suffix.equals(".xls") || suffix.equals(".xlsx")) { + } else if (suffix.equals(".xls") || suffix.equals(".xlsx")) { pic1.loadImage("../doccenter/com.awspaas.user.apps.coe.pal.output.zd/filepic/xls.png"); - paragraph5.appendText(dcContextModel.getFileName() + " "); - paragraph5.applyStyle(BuiltinStyle.Body_Text); + paragraph5.appendText(dcContextModel.getFileName()+" "); + paragraph5.applyStyle(BuiltinStyle.Body_Text); //应用标题1样式 if (suffix.equals(".xls")) { paragraph5.appendOleObject(stream1, pic1, "xls"); - continue; - } - if (suffix.equals(".xlsx")) + } else if (suffix.equals(".xlsx")) { paragraph5.appendOleObject(stream1, pic1, "xlsx"); - continue; - } - if (suffix.equals(".png") || suffix.equals(".jgp")) { + } + } else if (suffix.equals(".png") || suffix.equals(".jgp")) { pic1.loadImage("../doccenter/com.awspaas.user.apps.coe.pal.output.zd/filepic/png.png"); - paragraph5.appendText(dcContextModel.getFileName() + " "); - paragraph5.applyStyle(BuiltinStyle.Body_Text); + paragraph5.appendText(dcContextModel.getFileName()+" "); + paragraph5.applyStyle(BuiltinStyle.Body_Text); //应用标题1样式 if (suffix.equals(".png")) { paragraph5.appendOleObject(stream1, pic1, "png"); - continue; - } - if (suffix.equals(".jpg")) + } else if (suffix.equals(".jpg")) { paragraph5.appendOleObject(stream1, pic1, "jpg"); - continue; - } - if (suffix.equals(".zip") || suffix.equals(".rar")) { + } + } else if (suffix.equals(".zip") || suffix.equals(".rar")) { pic1.loadImage("../doccenter/com.awspaas.user.apps.coe.pal.output.zd/filepic/zip.png"); - paragraph5.appendText(dcContextModel.getFileName() + " "); - paragraph5.applyStyle(BuiltinStyle.Body_Text); + paragraph5.appendText(dcContextModel.getFileName()+" "); + paragraph5.applyStyle(BuiltinStyle.Body_Text); //应用标题1样式 if (suffix.equals(".zip")) { paragraph5.appendOleObject(stream1, pic1, "zip"); - continue; - } - if (suffix.equals(".rar")) + } else if (suffix.equals(".rar")) { paragraph5.appendOleObject(stream1, pic1, "rar"); - continue; - } - if (suffix.equals(".mp3") || suffix.equals(".mp4")) { + } + } else if (suffix.equals(".mp3") || suffix.equals(".mp4")) { pic1.loadImage("../doccenter/com.awspaas.user.apps.coe.pal.output.zd/filepic/mp3.png"); - paragraph5.appendText(dcContextModel.getFileName() + " "); - paragraph5.applyStyle(BuiltinStyle.Body_Text); + paragraph5.appendText(dcContextModel.getFileName()+" "); + paragraph5.applyStyle(BuiltinStyle.Body_Text); //应用标题1样式 if (suffix.equals(".mp3")) { paragraph5.appendOleObject(stream1, pic1, "mp3"); - continue; - } - if (suffix.equals(".mp4")) + } else if (suffix.equals(".mp4")) { paragraph5.appendOleObject(stream1, pic1, "mp4"); - continue; - } - if (suffix.equals(".ppt") || suffix.equals(".pptx")) { + } + } else if (suffix.equals(".ppt") || suffix.equals(".pptx")) { pic1.loadImage("../doccenter/com.awspaas.user.apps.coe.pal.output.zd/filepic/ppt.png"); - paragraph5.appendText(dcContextModel.getFileName() + " "); - paragraph5.applyStyle(BuiltinStyle.Body_Text); + paragraph5.appendText(dcContextModel.getFileName()+" "); + paragraph5.applyStyle(BuiltinStyle.Body_Text); //应用标题1样式 if (suffix.equals(".ppt")) { paragraph5.appendOleObject(stream1, pic1, "ppt"); - continue; - } - if (suffix.equals(".pptx")) + } else if (suffix.equals(".pptx")) { paragraph5.appendOleObject(stream1, pic1, "pptx"); - continue; - } - if (suffix.equals(".txt")) { + } + } else if (suffix.equals(".txt")) { pic1.loadImage("../doccenter/com.awspaas.user.apps.coe.pal.output.zd/filepic/txt.png"); - paragraph5.appendText(dcContextModel.getFileName() + " "); - paragraph5.applyStyle(BuiltinStyle.Body_Text); + paragraph5.appendText(dcContextModel.getFileName()+" "); + paragraph5.applyStyle(BuiltinStyle.Body_Text); //应用标题1样式 paragraph5.appendOleObject(stream1, pic1, "txt"); } + + } + } long b2 = System.currentTimeMillis(); - System.err.println("插入附件用时:" + ((b2 - b1) / 1000L) + "秒"); + System.err.println("插入附件用时:" + + (b2 - b1) / 1000 + "秒"); } + try { - System.out.println("Filed==================" + repositoryModel.getId()); + System.out.println("Filed=================="+repositoryModel.getId()); doc.saveToFile(outFile.getPath(), FileFormat.Docx_2013); } catch (Exception e) { e.printStackTrace(); } finally { + // 关闭文档对象 doc.close(); } - } - } - - // 针对横版页眉的特殊处理 - private static void processLandscapeHeader(HeaderFooter header, JSONObject dataMap) { - for (int c = 0; c < header.getChildObjects().getCount(); c++) { - DocumentObject childObj = header.getChildObjects().get(c); - - if (childObj instanceof Table) { - Table table = (Table) childObj; - // 横版可能需要对表格布局做特殊调整 - adjustTableForLandscape(table, dataMap); - } - // 其他横版特有的处理逻辑 - } - } - - - // 调整表格适应横版 - private static void adjustTableForLandscape(Table table, JSONObject dataMap) { - // 调整列宽比例 - if (table.getRows().getCount() > 0) { - TableRow row = table.getRows().get(0); - if (row.getCells().getCount() >= 2) { - row.getCells().get(0).setWidth(70f); - row.getCells().get(1).setWidth(70f); - - - } } - // 处理内容 - processTable(table, dataMap); - } - - // 处理表格中的占位符 - private static void processTable(Table table, JSONObject dataMap) { - for (int i = 0; i < table.getRows().getCount(); i++) { - TableRow row = table.getRows().get(i); - for (int j = 0; j < row.getCells().getCount(); j++) { - TableCell cell = row.getCells().get(j); - for (int k = 0; k < cell.getParagraphs().getCount(); k++) { - Paragraph paragraph = cell.getParagraphs().get(k); - processParagraph(paragraph, dataMap); - } - } - } } /** - * 判断是否为横向 + * 生成word文件 + * + * @param dataMap + * @param tempPath + * @param tempName + * @param docName */ - public static boolean isLandscapeBySize(double width, double height) { - return width > height; - } - - - // 处理段落中的占位符 - private static void processParagraph(Paragraph paragraph, JSONObject dataMap) { - for (int i = 0; i < paragraph.getChildObjects().getCount(); i++) { - DocumentObject paraChild = paragraph.getChildObjects().get(i); - - if (paraChild instanceof TextRange) { - // 处理文本占位符 - TextRange textRange = (TextRange) paraChild; - textRange.setText(dataMap.getString("HEADERFONT")); - } else if (paraChild instanceof DocPicture) { - // 处理图片占位符 - DocPicture picture = (DocPicture) paraChild; - processPicture(picture, dataMap); - } - // 可以添加其他类型的处理 - } - } - - - - // 替换占位符的具体实现 - private static String replacePlaceholders(String text, JSONObject dataMap) { - // 使用正则表达式匹配 ${...} 格式的占位符 - Pattern pattern = Pattern.compile("\\$\\{([^}]+)\\}"); - Matcher matcher = pattern.matcher(text); - StringBuffer result = new StringBuffer(); - - while (matcher.find()) { - String placeholder = matcher.group(1); // 获取占位符名称 - String replacement = dataMap.getString(placeholder); // 从数据映射中获取值 - - // 特殊处理LOGOURL,可能需要替换为图片 - if ("LOGOURL".equals(placeholder) && !replacement.isEmpty()) { - // 这里可以设置标志,后续处理图片 - replacement = "[LOGO_PLACEHOLDER]"; // 临时占位符 - } - - matcher.appendReplacement(result, Matcher.quoteReplacement(replacement)); - } - matcher.appendTail(result); - - return result.toString(); - } - - - // 处理图片 - private static void processPicture(DocPicture picture, JSONObject dataMap) { - // 检查图片是否有特殊标记或需要替换 - String altText = picture.getAlternativeText(); - if (altText != null && altText.contains("${LOGOURL}")) { - String logoUrl = dataMap.getString("LOGOURL"); - if (logoUrl != null && !logoUrl.isEmpty()) { - try { - // 重新设置图片 - picture.loadImage(logoUrl); - picture.setWidth(44.0F); - picture.setHeight(35.0F); - } catch (Exception e) { - System.out.println("图片加载失败: " + logoUrl); - } - } - } - } - - - - - private static void processImageCell(TableCell cell, String logoUrl) { - if (cell.getParagraphs().getCount() > 0) { - IParagraph firstParagraph = cell.getFirstParagraph(); - - // 清除段落中的所有现有内容 - firstParagraph.getChildObjects().clear(); - - try { - // 添加新图片 - DocPicture picture = firstParagraph.appendPicture(logoUrl); - picture.setWidth(44.0F); - picture.setHeight(35.0F); - - // 设置图片对齐方式 - firstParagraph.getFormat().setHorizontalAlignment(HorizontalAlignment.Right); - - } catch (Exception e) { - // 图片加载失败时添加文本占位符 - ITextRange textRange = firstParagraph.appendText("[图片加载失败]"); - textRange.getCharacterFormat().setTextColor(Color.RED); - textRange.getCharacterFormat().setItalic(true); - } - } - } - - - public static void createBdDoc2(JSONObject dataMap, String tempPath, String tempName, String docName, String repositoryId) throws FileNotFoundException { Configuration configuration = new Configuration(); configuration.setDefaultEncoding("UTF-8"); + + // 设置模本装置方法和路径 try { UtilFile temps = new UtilFile(tempPath); - configuration.setDirectoryForTemplateLoading((File)temps); + configuration.setDirectoryForTemplateLoading(temps); } catch (IOException e2) { e2.printStackTrace(); } @@ -1413,31 +1858,60 @@ public class OutputWordUtil { } catch (IOException e) { e.printStackTrace(); } + + //判断表单图是否为单一模型并且只上传excel一种附件,导出手册直接导出excel手册 PALRepositoryModel repositoryModel = PALRepositoryQueryAPIManager.getInstance().queryPalRepositoryModelByPalId(repositoryId); + UpFileDao upFileDao = new UpFileDao(); + //查询模型文件属性上传附件信息 List search = upFileDao.searchByRepositoryId(repositoryModel.getId(), "s"); - if (search.size() > 0) + + if (search.size() > 0) { if (search.size() == 1) { DCContext dcContextModel = null; - String getExcelFileName = ((UpfileModel)search.get(0)).getFileName(); + //获取 + String getExcelFileName = search.get(0).getFileName(); + + //获取文件的后缀名 int lastIndexOf = getExcelFileName.lastIndexOf("."); String suffix = getExcelFileName.substring(lastIndexOf); if (suffix.equals(".xls") || suffix.equals(".xlsx")) { - DCPluginProfile dcProfile = DCProfileManager.getDCProfile("com.actionsoft.apps.coe.pal", "COE_Upfile"); + + DCPluginProfile dcProfile = DCProfileManager.getDCProfile(CoEConstant.APP_ID, CoeFileConstant.COE_UPFILE); + UserContext userContext = DispatcherRequest.getUserContext(); + + String excelUrl = docName.substring(0, docName.lastIndexOf("/") + 1); + + // 调用App String sourceAppId = "com.actionsoft.apps.coe.pal"; + // aslp服务地址 String aslp = "aslp://com.awspaas.user.apps.new_performance_indicator_library/UpdatePptxAndExcelAslp"; + // 参数定义列表 Map params = new HashMap(); + //文件id,必填 params.put("pl_uuid", repositoryId); - params.put("shape_uuid",search.get(0).getShape_uuid()); + //文件内容id,必填 + params.put("shape_uuid", search.get(0).getShape_uuid()); + + //文件保存地址,必填 params.put("fil_path", excelUrl + search.get(0).getFileName()); + + //文件路径(不包含文件名称),必填 params.put("file_url", excelUrl); + + //文件名称,必填 params.put("file_data", search.get(0).getFileName()); + //sid,必填 params.put("sid", userContext.getSessionId()); AppAPI appAPI = SDK.getAppAPI(); - ResponseObject responseObject = appAPI.callASLP(appAPI.getAppContext(sourceAppId), aslp, params); + //根据上传的文件进行更新相关的excel或者ppt + ResponseObject ro = appAPI.callASLP(appAPI.getAppContext(sourceAppId), aslp, params); + + } else { + // 输出文档路径及名称 File outFile = new File(docName); Writer out = null; try { @@ -1445,6 +1919,7 @@ public class OutputWordUtil { } catch (Exception e1) { e1.printStackTrace(); } + try { if (t != null && out != null) { t.process(dataMap, out); @@ -1458,7 +1933,10 @@ public class OutputWordUtil { } ConcatenationformBySpire(outFile.getPath(), search); } + + } else { + // 输出文档路径及名称 File outFile = new File(docName); Writer out = null; try { @@ -1466,6 +1944,7 @@ public class OutputWordUtil { } catch (Exception e1) { e1.printStackTrace(); } + try { if (t != null && out != null) { t.process(dataMap, out); @@ -1479,143 +1958,188 @@ public class OutputWordUtil { } ConcatenationformBySpire(outFile.getPath(), search); } + } + + } + public static void ConcatenationformBySpire(String filePath, List search) throws FileNotFoundException { + /**************************************************插入文件对象**********************************************************************/ Document doc = new Document(filePath); + //获取最后一节 Section section = doc.getLastSection(); + + CharacterFormat format4 = new CharacterFormat(); + //创建字体格式 format4.setFontName("宋体"); + //添加段落 Paragraph paragraph = section.addParagraph(); + + ParagraphFormat paragraphFormat4 = paragraph.getFormat(); - paragraphFormat4.setHorizontalAlignment(HorizontalAlignment.Left); + paragraphFormat4.setHorizontalAlignment(Left); + TextRange tr4 = paragraph.appendText("表单/模板"); + tr4.getCharacterFormat().setBold(true); tr4.getCharacterFormat().setFontName("宋体"); - paragraph.applyStyle(BuiltinStyle.Heading_2); + paragraph.applyStyle(BuiltinStyle.Heading_2); //应用标题1样式 + + //doc.saveToFile(outFile.getPath(), FileFormat.Docx_2013); + + DCContext dcContextModel = null; UserContext userContext = DispatcherRequest.getUserContext(); if (search != null && search.size() > 0) { + //插入前,附件名先排序先排序 sortFilesByNumber(search); + // 复制附件 for (UpfileModel upfileModel : search) { - DCPluginProfile dcProfile = DCProfileManager.getDCProfile("com.actionsoft.apps.coe.pal", "COE_Upfile"); + DCPluginProfile dcProfile = DCProfileManager.getDCProfile(CoEConstant.APP_ID, CoeFileConstant.COE_UPFILE); + if (dcProfile != null) { - dcContextModel = new DCContext(userContext, dcProfile, "com.actionsoft.apps.coe.pal", upfileModel.getPl_uuid(), upfileModel.getShape_uuid(), upfileModel.getFileName()); + dcContextModel = new DCContext(userContext, dcProfile, CoEConstant.APP_ID, upfileModel.getPl_uuid(), upfileModel.getShape_uuid(), upfileModel.getFileName()); String path = dcContextModel.getPath(); String fileName = dcContextModel.getFileName(); + + + //添加段落 Paragraph paragraph5 = section.addParagraph(); + + //加载一个图片,它将作为外部文件的符号显示在Word文档中 + //获取最后一个.的位置 int lastIndexOf = dcContextModel.getFileName().lastIndexOf("."); + //获取文件的后缀名 .jpg String suffix = dcContextModel.getFileName().substring(lastIndexOf); - DocPicture pdfIcon = new DocPicture((IDocument)doc); + + DocPicture pdfIcon = new DocPicture(doc); + InputStream stream1 = new FileInputStream(dcContextModel.getFilePath()); - DocPicture pic1 = new DocPicture((IDocument)doc); + DocPicture pic1 = new DocPicture(doc); + if (suffix.equals(".doc") || suffix.equals(".docx")) { pic1.loadImage("../doccenter/com.awspaas.user.apps.coe.pal.output.zd/filepic/word.png"); - paragraph5.appendText(dcContextModel.getFileName() + " "); + paragraph5.appendText(dcContextModel.getFileName()+" "); if (suffix.equals(".doc")) { paragraph5.appendOleObject(stream1, pic1, "doc"); - continue; - } - if (suffix.equals(".docx")) + } else if (suffix.equals(".docx")) { paragraph5.appendOleObject(stream1, pic1, "docx"); - continue; - } - if (suffix.equals(".pdf")) { + } + } else if (suffix.equals(".pdf")) { pic1.loadImage("../doccenter/com.awspaas.user.apps.coe.pal.output.zd/filepic/pdf.png"); - paragraph5.appendText(dcContextModel.getFileName() + " "); + paragraph5.appendText(dcContextModel.getFileName()+" "); paragraph5.appendOleObject(stream1, pic1, "pdf"); - continue; - } - if (suffix.equals(".xls") || suffix.equals(".xlsx")) { + } else if (suffix.equals(".xls") || suffix.equals(".xlsx")) { pic1.loadImage("../doccenter/com.awspaas.user.apps.coe.pal.output.zd/filepic/xls.png"); - paragraph5.appendText(dcContextModel.getFileName() + " "); + paragraph5.appendText(dcContextModel.getFileName()+" "); if (suffix.equals(".xls")) { paragraph5.appendOleObject(stream1, pic1, "xls"); - continue; - } - if (suffix.equals(".xlsx")) + } else if (suffix.equals(".xlsx")) { paragraph5.appendOleObject(stream1, pic1, "xlsx"); - continue; - } - if (suffix.equals(".png") || suffix.equals(".jgp")) { + } + } else if (suffix.equals(".png") || suffix.equals(".jgp")) { pic1.loadImage("../doccenter/com.awspaas.user.apps.coe.pal.output.zd/filepic/png.png"); - paragraph5.appendText(dcContextModel.getFileName() + " "); + paragraph5.appendText(dcContextModel.getFileName()+" "); if (suffix.equals(".png")) { paragraph5.appendOleObject(stream1, pic1, "png"); - continue; - } - if (suffix.equals(".jpg")) + } else if (suffix.equals(".jpg")) { paragraph5.appendOleObject(stream1, pic1, "jpg"); - continue; - } - if (suffix.equals(".zip") || suffix.equals(".rar")) { + } + } else if (suffix.equals(".zip") || suffix.equals(".rar")) { pic1.loadImage("../doccenter/com.awspaas.user.apps.coe.pal.output.zd/filepic/zip.png"); - paragraph5.appendText(dcContextModel.getFileName() + " "); + paragraph5.appendText(dcContextModel.getFileName()+" "); if (suffix.equals(".zip")) { paragraph5.appendOleObject(stream1, pic1, "zip"); - continue; - } - if (suffix.equals(".rar")) + } else if (suffix.equals(".rar")) { paragraph5.appendOleObject(stream1, pic1, "rar"); - continue; - } - if (suffix.equals(".mp3") || suffix.equals(".mp4")) { + } + } else if (suffix.equals(".mp3") || suffix.equals(".mp4")) { pic1.loadImage("../doccenter/com.awspaas.user.apps.coe.pal.output.zd/filepic/mp3.png"); - paragraph5.appendText(dcContextModel.getFileName() + " "); + paragraph5.appendText(dcContextModel.getFileName()+" "); if (suffix.equals(".mp3")) { paragraph5.appendOleObject(stream1, pic1, "mp3"); - continue; - } - if (suffix.equals(".mp4")) + } else if (suffix.equals(".mp4")) { paragraph5.appendOleObject(stream1, pic1, "mp4"); - continue; - } - if (suffix.equals(".txt")) { + } + } else if (suffix.equals(".txt")) { pic1.loadImage("../doccenter/com.awspaas.user.apps.coe.pal.output.zd/filepic/txt.png"); - paragraph5.appendText(dcContextModel.getFileName() + " "); + paragraph5.appendText(dcContextModel.getFileName()+" "); paragraph5.appendOleObject(stream1, pic1, "txt"); } + + } } + } + doc.saveToFile(filePath, FileFormat.Docx_2013); } + /** + * 将文件的扩展属性设置默认值为空字符串(防止没有设置扩展属性而使得导出文件出错) + * + * @param methodScope + * @param dataMap + */ public static void setRepositoryDefaultValue(String methodScope, JSONObject dataMap) { - List attributes = new ArrayList<>(); + List attributes = new ArrayList(); String[] methodIds = methodScope.split(","); for (String methodId : methodIds) { PALMethodModel palMethodModel = PALMethodCache.getPALMethodModelById(methodId); - if (palMethodModel != null) + if (palMethodModel != null) { attributes.addAll(palMethodModel.getAttributes()); + } } - if (attributes != null) + + if (attributes != null) { for (PALMethodAttributeModel attribute : attributes) { String scope = attribute.getScope(); - if (scope.indexOf("%") > -1) + if (scope.indexOf("%") > -1) { dataMap.put("pl_" + attribute.getKey(), ""); + } } + } } + /** + * 将文件的扩展属性设置默认值为空字符串(防止没有设置扩展属性而使得导出文件出错) + * com.alibaba.fastjson + * + * @param methodScope + * @param dataMap + */ public static void setRepositoryDefaultValue2(String methodScope, JSONObject dataMap) { - List attributes = new ArrayList<>(); + List attributes = new ArrayList(); String[] methodIds = methodScope.split(","); for (String methodId : methodIds) { PALMethodModel palMethodModel = PALMethodCache.getPALMethodModelById(methodId); - if (palMethodModel != null) + if (palMethodModel != null) { attributes.addAll(palMethodModel.getAttributes()); + } } - if (attributes != null) + + if (attributes != null) { for (PALMethodAttributeModel attribute : attributes) { String scope = attribute.getScope(); - if (scope.indexOf("%") > -1) + if (scope.indexOf("%") > -1) { dataMap.put("pl_" + attribute.getKey(), ""); + } } + } } + /** + * 将文件中图形元素的扩展属性默认值设为空字符串(防止没有设置扩展属性而使得导出文件出错) + * + * @param repositoryId + * @param _tr + */ public static void setShapeDefaultValue(String repositoryId, JSONObject _tr) { - List attributes = new ArrayList<>(); - PALRepositoryModel repositoryModel = (PALRepositoryModel)PALRepositoryCache.getCache().get(repositoryId); + List attributes = new ArrayList(); + PALRepositoryModel repositoryModel = PALRepositoryCache.getCache().get(repositoryId); String methodId = repositoryModel.getMethodId(); if ("control".equals(methodId.substring(0, methodId.indexOf(".")))) { PALMethodModel palMethodModel_kpi = PALMethodCache.getPALMethodModelById("control.kpi"); @@ -1628,23 +2152,32 @@ public class OutputWordUtil { PALMethodModel palMethodModel = PALMethodCache.getPALMethodModelById(repositoryModel.getMethodId()); attributes.addAll(palMethodModel.getAttributes()); } - _tr.put("shape_number", ""); - _tr.put("shape_name", ""); - if (attributes != null) + + _tr.put(OutputWordUtil.SHAPE_NUMBER, ""); + _tr.put(OutputWordUtil.SHAPE_NAME, ""); + if (attributes != null) { for (PALMethodAttributeModel attribute : attributes) { String scope = attribute.getScope(); - if (!"%".equals(scope)) + if (!"%".equals(scope)) { _tr.put("shape_" + attribute.getKey(), ""); + } if ("organization".equals(attribute.getGroupPath())) { _tr.put("shape_" + attribute.getKey() + "_org", ""); _tr.put("shape_" + attribute.getKey() + "_role", ""); } } + } } + /** + * 将文件中图形元素的扩展属性默认值设为空字符串(防止没有设置扩展属性而使得导出文件出错) + * + * @param repositoryId + * @param _tr + */ public static void setShapeDefaultValue2(String repositoryId, JSONObject _tr) { - List attributes = new ArrayList<>(); - PALRepositoryModel repositoryModel = (PALRepositoryModel)PALRepositoryCache.getCache().get(repositoryId); + List attributes = new ArrayList(); + PALRepositoryModel repositoryModel = PALRepositoryCache.getCache().get(repositoryId); String methodId = repositoryModel.getMethodId(); if ("control".equals(methodId.substring(0, methodId.indexOf(".")))) { PALMethodModel palMethodModel_kpi = PALMethodCache.getPALMethodModelById("control.kpi"); @@ -1657,85 +2190,217 @@ public class OutputWordUtil { PALMethodModel palMethodModel = PALMethodCache.getPALMethodModelById(repositoryModel.getMethodId()); attributes.addAll(palMethodModel.getAttributes()); } - _tr.put("shape_number", ""); - _tr.put("shape_name", ""); - if (attributes != null) + + _tr.put(OutputWordUtil.SHAPE_NUMBER, ""); + _tr.put(OutputWordUtil.SHAPE_NAME, ""); + if (attributes != null) { for (PALMethodAttributeModel attribute : attributes) { String scope = attribute.getScope(); - if (!"%".equals(scope)) + if (!"%".equals(scope)) { _tr.put("shape_" + attribute.getKey(), ""); + } if ("organization".equals(attribute.getGroupPath())) { _tr.put("shape_" + attribute.getKey() + "_org", ""); _tr.put("shape_" + attribute.getKey() + "_role", ""); } } + } } + /** + * 字符串去重(Set本身有去重功能) + * + * @param str 要去重的字符串 + * @param separator 分隔符 + * @return + */ public static String removeRepeat(String str, String separator) { Set set = string2set(str, separator); return set2string(set); } public static Set string2set(String str, String separator) { - Set set = new LinkedHashSet<>(); + Set set = new LinkedHashSet(); if (str != null && !"".equals(str)) { String[] array = str.split(separator); - for (String string : array) + for (String string : array) { set.add(string); + } } return set; } public static String set2string(Set set) { StringBuilder result = new StringBuilder(); - if (set.size() > 0) + if (set.size() > 0) { for (Iterator it = set.iterator(); it.hasNext(); ) { result.append(it.next()); result.append(","); } - if (result.indexOf(",") != -1) + } + + if (result.indexOf(",") != -1) { return result.substring(0, result.length() - 1); - return result.toString(); + } else { + return result.toString(); + } } + /** + * 如果图形元素属性中有关联的图形,获取关联的流程文件的数据Table + * + * @param table + * @param relationShapeIds + */ @Deprecated public static void setTableValue(JSONArray table, String relationShapeIds) { relationShapeIds = relationShapeIds.replace("[", "").replace("]", "").replace("\"", ""); String[] relationShapeIdArray = relationShapeIds.split(","); - List relationModelList = new ArrayList<>(); + List relationModelList = new ArrayList(); DesignerShapeRelationDao dao = new DesignerShapeRelationDao(); for (String relationShapeId : relationShapeIdArray) { - if (!UtilString.isEmpty(relationShapeId)) { - List relationModels = dao.query(null, null, null, null, relationShapeId); - if (relationModels != null && relationModels.size() > 0) - relationModelList.addAll(relationModels); + if (UtilString.isEmpty(relationShapeId)) { + continue; + } + List relationModels = dao.query(null, null, null, null, relationShapeId); + if (relationModels != null && relationModels.size() > 0) { + relationModelList.addAll(relationModels); } } + if (relationModelList != null && relationModelList.size() > 0) { int index = 1; for (DesignerShapeRelationModel repositoryShape : relationModelList) { String relationFileId = repositoryShape.getRelationFileId(); - if (relationFileId == null || "".equals(relationFileId)) + if (relationFileId == null || "".equals(relationFileId)) { continue; - List> relationFileElements = CoeDesignerUtil.getShapeMessageJson2(relationFileId); - if (relationFileElements == null || relationFileElements.size() == 0) + } + List> relationFileElements = CoeDesignerUtil.getShapeMessageJson2(relationFileId); // 关联流程文件内容 + if (relationFileElements == null || relationFileElements.size() == 0) { continue; + } + for (Map element : relationFileElements) { - String id = (String)element.get("id"); + String id = (String) element.get("id"); if (relationShapeIds.indexOf(id) != -1) { JSONObject _tr = new JSONObject(); - setShapeDefaultValue(repositoryShape.getRelationFileId(), _tr); + OutputWordUtil.setShapeDefaultValue(repositoryShape.getRelationFileId(), _tr); String name = element.get("text").toString(); - _tr.put("shape_name", name.replace("\n", "")); - _tr.put("serial_number", Integer.valueOf(index)); - JSONObject dataAttributes = (JSONObject)element.get("attributes"); + _tr.put(OutputWordUtil.SHAPE_NAME, name.replace("\n", OutputWordUtil.WRAPSTRING)); + _tr.put(OutputWordUtil.SERIAL_NUMBER, index); + + JSONObject dataAttributes = (JSONObject) element.get("attributes"); if (dataAttributes != null) { JSONArray dataAttributesJsonArray = dataAttributes.getJSONArray("attributesJsonArray"); for (int i = 0; i < dataAttributesJsonArray.size(); i++) { JSONObject dataAttribute = dataAttributesJsonArray.getJSONObject(i); - if (dataAttribute != null && !"null".equals(dataAttribute.toString())) - if (dataAttribute.containsKey("key") && dataAttribute.containsKey("value")) - _tr.put("shape_" + dataAttribute.getString("key"), dataAttribute.getString("value")); + if (dataAttribute == null || "null".equals(dataAttribute.toString())) { + continue; //跳过dataAttributesJsonArray中的空 + } + if (dataAttribute.containsKey("key") && dataAttribute.containsKey("value")) { + _tr.put("shape_" + dataAttribute.getString("key"), dataAttribute.getString("value")); + } + } + if (dataAttributes.containsKey("privateAttributeContent")) { + String privateAttributeContentStr = dataAttributes.get("privateAttributeContent").toString(); + //basic类型的privateAttributeContent属性为“[]”,其他类型模型的该属性为JSONObject格式 + if (!"".equals(privateAttributeContentStr) && !"[]".equals(privateAttributeContentStr)) { + String firstChart = privateAttributeContentStr.substring(0, 1); + if ("{".equals(firstChart)) { + JSONObject privateAttributeContent = dataAttributes.getJSONObject("privateAttributeContent"); + for (String key : privateAttributeContent.keySet()) { + _tr.put("shape_" + key, privateAttributeContent.getString(key)); + } + // Iterator it = privateAttributeContent.keys(); + // while (it.hasNext()) { + // String key = (String) it.next(); + // _tr.put("shape_" + key, privateAttributeContent.getString(key)); + // } + } + } + } + } + + table.add(_tr); + index++; + relationShapeIds = relationShapeIds.replace(id, ""); + } + } + } + + } + } + + /** + * 如果图形元素属性中有关联的图形,获取关联的流程文件的数据Table + * com.alibaba.fastjson + * + * @param repositoryId + * @param table + * @param relationShapeIds + */ + @Deprecated + public static void setTableValue2(String repositoryId, JSONArray table, String relationShapeIds) { + // 记录关联属性的流程节点,防止多次查询重复文件信息耗费时间 + Set relationFileIds = new HashSet<>(); + List> relationFileElements2 = new ArrayList>(); + + relationShapeIds = relationShapeIds.replace("[", "").replace("]", "").replace("\"", ""); + if (!"".equals(relationShapeIds)) { + String[] relationShapeIdArray = relationShapeIds.split(","); + Set relationShapeIdSet = new HashSet<>(Arrays.asList(relationShapeIdArray)); // 去重 + Set fileIdSet = new HashSet<>(); + DesignerShapeRelationDao dao = new DesignerShapeRelationDao(); + for (String relationShapeId : relationShapeIdSet) { + List relationModels = dao.query(repositoryId, null, null, null, relationShapeId); + if (relationModels != null && relationModels.size() > 0) { + for (int i = 0; i < relationModels.size(); i++) { + String relationFileId = relationModels.get(i).getRelationFileId(); + if (relationFileId == null || "".equals(relationFileId)) { + continue; + } + if (!fileIdSet.contains(relationFileId)) { + fileIdSet.add(relationFileId); + } + } + } + } + + if (fileIdSet.size() > 0) { + for (String fileId : fileIdSet) { + if (relationFileIds.contains(fileId)) {// 该文件已查询过,不再重复查询 + + } else { + List> fileElements = CoeDesignerUtil.getShapeMessageJson2(fileId); // 关联流程文件内容 + if (fileElements != null && fileElements.size() > 0) { + relationFileIds.add(fileId); + relationFileElements2.addAll(fileElements); + } + } + } + } + int index = 1; + for (String relationShapeId : relationShapeIdSet) { + for (Map element : relationFileElements2) { + String id = (String) element.get("id"); + if (relationShapeId.equals(id)) { + JSONObject _tr = new JSONObject(); + OutputWordUtil.setShapeDefaultValue2((String) element.get("pid"), _tr); + String name = specialCharTransfer(element.get("text").toString()); + _tr.put(OutputWordUtil.SHAPE_NAME, name.replace("\n", OutputWordUtil.WRAPSTRING)); + _tr.put(OutputWordUtil.SERIAL_NUMBER, index); + + JSONObject dataAttributes = (JSONObject) element.get("attributes"); + if (dataAttributes != null) { + JSONArray dataAttributesJsonArray = dataAttributes.getJSONArray("attributesJsonArray"); + for (int i = 0; i < dataAttributesJsonArray.size(); i++) { + JSONObject dataAttribute = dataAttributesJsonArray.getJSONObject(i); + if (dataAttribute == null || "null".equals(dataAttribute.toString())) { + continue; + } + if (dataAttribute.containsKey("key") && dataAttribute.containsKey("value")) { + _tr.put("shape_" + dataAttribute.getString("key"), specialCharTransfer(dataAttribute.getString("value"))); + } } if (dataAttributes.containsKey("privateAttributeContent")) { String privateAttributeContentStr = dataAttributes.get("privateAttributeContent").toString(); @@ -1743,153 +2408,108 @@ public class OutputWordUtil { String firstChart = privateAttributeContentStr.substring(0, 1); if ("{".equals(firstChart)) { JSONObject privateAttributeContent = dataAttributes.getJSONObject("privateAttributeContent"); - for (String key : privateAttributeContent.keySet()) - _tr.put("shape_" + key, privateAttributeContent.getString(key)); - } - } - } - } - table.add(_tr); - index++; - relationShapeIds = relationShapeIds.replace(id, ""); - } - } - } - } - } - - @Deprecated - public static void setTableValue2(String repositoryId, JSONArray table, String relationShapeIds) { - Set relationFileIds = new HashSet<>(); - List> relationFileElements2 = new ArrayList<>(); - relationShapeIds = relationShapeIds.replace("[", "").replace("]", "").replace("\"", ""); - if (!"".equals(relationShapeIds)) { - String[] relationShapeIdArray = relationShapeIds.split(","); - Set relationShapeIdSet = new HashSet<>(Arrays.asList(relationShapeIdArray)); - Set fileIdSet = new HashSet<>(); - DesignerShapeRelationDao dao = new DesignerShapeRelationDao(); - for (String relationShapeId : relationShapeIdSet) { - List relationModels = dao.query(repositoryId, null, null, null, relationShapeId); - if (relationModels != null && relationModels.size() > 0) - for (int i = 0; i < relationModels.size(); i++) { - String relationFileId = ((DesignerShapeRelationModel)relationModels.get(i)).getRelationFileId(); - if (relationFileId != null && !"".equals(relationFileId)) - if (!fileIdSet.contains(relationFileId)) - fileIdSet.add(relationFileId); - } - } - if (fileIdSet.size() > 0) - for (String fileId : fileIdSet) { - if (relationFileIds.contains(fileId)) - continue; - List> fileElements = CoeDesignerUtil.getShapeMessageJson2(fileId); - if (fileElements != null && fileElements.size() > 0) { - relationFileIds.add(fileId); - relationFileElements2.addAll(fileElements); - } - } - int index = 1; - label75: for (String relationShapeId : relationShapeIdSet) { - for (Map element : relationFileElements2) { - String id = (String)element.get("id"); - if (relationShapeId.equals(id)) { - JSONObject _tr = new JSONObject(); - setShapeDefaultValue2((String)element.get("pid"), _tr); - String name = specialCharTransfer(element.get("text").toString()); - _tr.put("shape_name", name.replace("\n", "")); - _tr.put("serial_number", Integer.valueOf(index)); - JSONObject dataAttributes = (JSONObject)element.get("attributes"); - if (dataAttributes != null) { - JSONArray dataAttributesJsonArray = dataAttributes.getJSONArray("attributesJsonArray"); - for (int i = 0; i < dataAttributesJsonArray.size(); i++) { - JSONObject dataAttribute = dataAttributesJsonArray.getJSONObject(i); - if (dataAttribute != null && !"null".equals(dataAttribute.toString())) - if (dataAttribute.containsKey("key") && dataAttribute.containsKey("value")) - _tr.put("shape_" + dataAttribute.getString("key"), specialCharTransfer(dataAttribute.getString("value"))); - } - if (dataAttributes.containsKey("privateAttributeContent")) { - String privateAttributeContentStr = dataAttributes.get("privateAttributeContent").toString(); - if (!"".equals(privateAttributeContentStr)) { - if (!"[]".equals(privateAttributeContentStr)) { - String firstChart = privateAttributeContentStr.substring(0, 1); - if ("{".equals(firstChart)) { - JSONObject privateAttributeContent = dataAttributes.getJSONObject("privateAttributeContent"); - for (String key : privateAttributeContent.keySet()) - _tr.put("shape_" + key, specialCharTransfer(privateAttributeContent.getString(key))); - continue label75; + for (String key : privateAttributeContent.keySet()) { + _tr.put("shape_" + key, specialCharTransfer(privateAttributeContent.getString(key))); } - continue label75; } - continue label75; } - continue label75; } - continue label75; } + table.add(_tr); index++; + break; } } } } + } + /** + * 获取一行数据信息(包括扩展属性) + * + * @param _tr + * @param shapeIds + * @param key + */ @Deprecated public static void setTrValue(JSONObject _tr, String shapeIds, String key, Map shapeModelMap) { shapeIds = shapeIds.replace("[", "").replace("]", "").replace("\"", ""); shapeIds = removeRepeat(shapeIds, ","); String[] shapeIdArray = shapeIds.split(","); - List relationModelList = new ArrayList<>(); + List relationModelList = new ArrayList(); DesignerShapeRelationDao dao = new DesignerShapeRelationDao(); for (String shapeId : shapeIdArray) { List relationModels = dao.query(null, null, null, null, shapeId); - if (relationModels != null && relationModels.size() > 0) + if (relationModels != null && relationModels.size() > 0) { relationModelList.addAll(relationModels); + } } + StringBuffer sbOrg = new StringBuffer(""); StringBuffer sbRole = new StringBuffer(""); - if (relationModelList != null && relationModelList.size() > 0) + + if (relationModelList != null && relationModelList.size() > 0) { for (DesignerShapeRelationModel repositoryShape : relationModelList) { - if (!shapeModelMap.containsKey(repositoryShape.getRelationShapeId())) + if (!shapeModelMap.containsKey(repositoryShape.getRelationShapeId())) { continue; + } + String relationFileId = repositoryShape.getRelationFileId(); - List> relationFileElements = CoeDesignerUtil.getShapeMessageJson2(relationFileId); - if (relationFileElements != null) + List> relationFileElements = CoeDesignerUtil.getShapeMessageJson2(relationFileId); // 关联流程文件内容 + if (relationFileElements != null) { for (Map element : relationFileElements) { - String id = (String)element.get("id"); + String id = (String) element.get("id"); if (shapeIds.indexOf(id) != -1) { String type = element.get("type").toString(); if ("organization".equals(type)) { - sbOrg.append(element.get("text").toString().replace("\n", "")); + sbOrg.append(element.get("text").toString().replace("\n", OutputWordUtil.WRAPSTRING)); sbOrg.append(","); } else if ("position".equals(type) || "role".equals(type)) { - sbRole.append(element.get("text").toString().replace("\n", "")); + sbRole.append(element.get("text").toString().replace("\n", OutputWordUtil.WRAPSTRING)); sbRole.append(","); } - JSONObject dataAttributes = (JSONObject)element.get("attributes"); + + JSONObject dataAttributes = (JSONObject) element.get("attributes"); if (dataAttributes != null) { JSONArray dataAttributesJsonArray = dataAttributes.getJSONArray("attributesJsonArray"); for (int i = 0; i < dataAttributesJsonArray.size(); i++) { JSONObject dataAttribute = dataAttributesJsonArray.getJSONObject(i); - if (dataAttribute != null && !"null".equals(dataAttribute.toString())) - if (dataAttribute.containsKey("key") && dataAttribute.containsKey("value")) - _tr.put("shape_" + dataAttribute.getString("key"), dataAttribute.getString("value")); + if (dataAttribute == null || "null".equals(dataAttribute.toString())) { + continue; + } + if (dataAttribute.containsKey("key") && dataAttribute.containsKey("value")) { + _tr.put("shape_" + dataAttribute.getString("key"), dataAttribute.getString("value")); + } } } shapeIds = shapeIds.replace(id, ""); } } + } } + + } String sbOrgString = sbOrg.toString(); - if (sbOrgString.lastIndexOf(",") > 0) + if (sbOrgString.lastIndexOf(",") > 0) { sbOrgString = sbOrgString.substring(0, sbOrgString.length() - 1); + } String sbRoleString = sbRole.toString(); - if (sbRoleString.lastIndexOf(",") > 0) + if (sbRoleString.lastIndexOf(",") > 0) { sbRoleString = sbRoleString.substring(0, sbRoleString.length() - 1); + } _tr.put(key + "_org", sbOrgString); _tr.put(key + "_role", sbRoleString); } + /** + * 获取一行地址簿相关的数据信息 + * + * @param _tr + * @param shapeIds + * @param key + */ @Deprecated public static void setTrAwsOrgValue(JSONObject _tr, String shapeIds, String key, Map shapeModelMap) { shapeIds = shapeIds.replace("[", "").replace("]", "").replace("\"", ""); @@ -1902,72 +2522,108 @@ public class OutputWordUtil { String text = shapeModelMap.get(keyId); JSONObject object = JSONObject.parseObject(text); String type = object.getString("type"); - if ("department".equals(type)) { + if ("department".equals(type)) {// 部门 DepartmentModel deptModel = SDK.getORGAPI().getDepartmentById(keyId); - if (deptModel != null) + if (deptModel != null) { sbOrg.append(specialCharTransfer(deptModel.getName())).append(","); + } } - if ("user".equals(type)) { + if ("user".equals(type)) {// 人员 UserModel userModel = SDK.getORGAPI().getUser(keyId); - if (userModel != null) + if (userModel != null) { sbOrg.append(specialCharTransfer(userModel.getUserName())).append(","); + } } - if ("role".equals(type)) { + if ("role".equals(type)) {// 角色 RoleModel roleModel = SDK.getORGAPI().getRoleById(keyId); - if (roleModel != null) + if (roleModel != null) { sbRole.append(specialCharTransfer(roleModel.getName())).append(","); + } } } } String sbOrgString = sbOrg.toString(); - if (sbOrgString.lastIndexOf(",") > 0) + if (sbOrgString.lastIndexOf(",") > 0) { sbOrgString = sbOrgString.substring(0, sbOrgString.length() - 1); + } String sbRoleString = sbRole.toString(); - if (sbRoleString.lastIndexOf(",") > 0) + if (sbRoleString.lastIndexOf(",") > 0) { sbRoleString = sbRoleString.substring(0, sbRoleString.length() - 1); + } _tr.put(key + "_org", sbOrgString); _tr.put(key + "_role", sbRoleString); } + /** + * 获取图形实例的关联Model Map + * + * @param shapeId + * @return + */ @Deprecated public static Map getShapeRelationMap(String shapeId) { - Map relationMap = new HashMap<>(); + Map relationMap = new HashMap(); DesignerShapeRelationDao dao = new DesignerShapeRelationDao(); List relationModels = dao.query(null, shapeId, null, null, null); - if (relationModels != null && relationModels.size() > 0) - for (DesignerShapeRelationModel model : relationModels) + if (relationModels != null && relationModels.size() > 0) { + for (DesignerShapeRelationModel model : relationModels) { relationMap.put(model.getRelationShapeId(), model.getRelationShapeText()); + } + } return relationMap; } + /** + * 获取图形实例的关联Model Map + * + * @param shapeId + * @return + */ @Deprecated public static Map getShapeRelationMap(String fileId, String shapeId) { - Map relationMap = new HashMap<>(); + Map relationMap = new HashMap(); DesignerShapeRelationDao dao = new DesignerShapeRelationDao(); List relationModels = dao.query(fileId, shapeId, null, null, null); - if (relationModels != null && relationModels.size() > 0) + if (relationModels != null && relationModels.size() > 0) { for (DesignerShapeRelationModel model : relationModels) { if ("00000000-0000-0000-0000-000000000000".equals(model.getRelationFileId()) && "00000000-0000-0000-0000-000000000000".equals(model.getRelationShapeId())) { String text = model.getRelationShapeText(); relationMap.put(JSONObject.parseObject(text).getString("id"), text); - continue; + } else { + relationMap.put(model.getRelationShapeId(), model.getRelationShapeText()); } - relationMap.put(model.getRelationShapeId(), model.getRelationShapeText()); } + } return relationMap; } + /** + * 获取图形实例的关联Model Map + * + * @param fileId + * @param shapeId + * @return + */ public static Map> getShapeRelationAttrMap(String fileId, String shapeId) { - List list = (new DesignerShapeRelationDao()).query(fileId, shapeId, null, null, null); + List list = new DesignerShapeRelationDao().query(fileId, shapeId, null, null, null); Map> map = new HashMap<>(); for (DesignerShapeRelationModel model : list) { - if (!map.containsKey(model.getAttrId())) - map.put(model.getAttrId(), new ArrayList<>()); - ((List)map.get(model.getAttrId())).add(model); + if (!map.containsKey(model.getAttrId())) { + map.put(model.getAttrId(), new ArrayList()); + } + map.get(model.getAttrId()).add(model); } return map; } + /** + * 将图形元素关联属性的id替换为name + * + * @param key + * @param dataAttribute 图形元素所有关联属性 + * @param shapeRelationModelMap + * @return + */ @Deprecated public static void setShapeValue(JSONObject _tr, JSONObject dataAttribute, Map shapeRelationModelMap) { String result = ""; @@ -1976,28 +2632,46 @@ public class OutputWordUtil { result = dataAttribute.getString("value"); } else { StringBuilder keyValue = new StringBuilder(); - List keyValueList = new ArrayList<>(); + List keyValueList = new ArrayList(); if (key != null) { String attributeValue = dataAttribute.getString("value"); if (attributeValue != null && attributeValue.length() != 0) { attributeValue = attributeValue.replace("[", "").replace("]", "").replace("\"", ""); String[] keyValues = removeRepeat(attributeValue, ",").split(","); for (String keyId : keyValues) { - if (!"".equals(keyId) && shapeRelationModelMap.containsKey(keyId)) + if (!"".equals(keyId) && shapeRelationModelMap.containsKey(keyId)) { keyValueList.add(shapeRelationModelMap.get(keyId)); + } } - for (String value : keyValueList) + for (String value : keyValueList) { keyValue.append(value + ","); - if (keyValue.length() > 0) + } + + if (keyValue.length() > 0) { result = keyValue.toString().substring(0, keyValue.length() - 1); + } } } } - _tr.put("shape_" + key, result.replace("\n", "")); + + _tr.put("shape_" + key, result.replace("\n", OutputWordUtil.WRAPSTRING)); } + /** + * 查询横版特殊信息 + *

+ * 查询部门、岗位、角色 + *

+ * 部门、岗位、角色的区分依据在相应的流程源文件,需要查找源文件 + * + * @param _tr + * @param dataAttribute + * @param shapeModelMap + * @param relationFileElements + */ @Deprecated - public static void setRelationShapeValueByOrgAndRole(JSONObject _tr, JSONObject dataAttribute, Map shapeModelMap, List> relationFileElements, String shapeId, Set relationFileIds) { + public static void setRelationShapeValueByOrgAndRole(JSONObject _tr, JSONObject dataAttribute, + Map shapeModelMap, List> relationFileElements, String shapeId, Set relationFileIds) { String key = dataAttribute.getString("key"); if ("organization".equals(dataAttribute.getString("groupPath")) && "relation".equals(dataAttribute.getString("type"))) { String relationShapeIds = dataAttribute.getString("value"); @@ -2006,61 +2680,73 @@ public class OutputWordUtil { String[] relationShapeIdArr = relationShapeIds.split(","); DesignerShapeRelationDao dao = new DesignerShapeRelationDao(); for (String str : relationShapeIdArr) { - if (shapeModelMap.containsKey(str)) { - List relationModels = dao.query(null, shapeId, key, null, str); - if (relationModels != null && relationModels.size() > 0) - for (DesignerShapeRelationModel model : relationModels) { - String relationFileId = model.getRelationFileId(); - boolean flag = false; - if (relationFileIds.contains(relationFileId)) { + if (!shapeModelMap.containsKey(str)) { + continue; + } + List relationModels = dao.query(null, shapeId, key, null, str); + if (relationModels != null && relationModels.size() > 0) { + for (DesignerShapeRelationModel model : relationModels) { + String relationFileId = model.getRelationFileId(); + boolean flag = false; + if (relationFileIds.contains(relationFileId)) {// 包含该关联文件内容,不再查询 + flag = true; + } else {// 不包含该文件,查询 + List> FileElements = CoeDesignerUtil.getShapeMessageJson2(relationFileId); // 关联流程文件内容 + if (FileElements != null) { + relationFileIds.add(relationFileId); + relationFileElements.addAll(FileElements); flag = true; - } else { - List> FileElements = CoeDesignerUtil.getShapeMessageJson2(relationFileId); - if (FileElements != null) { - relationFileIds.add(relationFileId); - relationFileElements.addAll(FileElements); - flag = true; - } - } - if (flag) { - StringBuilder sbOrg = new StringBuilder(_tr.getString("shape_" + key + "_org")); - StringBuilder sbRole = new StringBuilder(_tr.getString("shape_" + key + "_role")); - for (Map element : relationFileElements) { - String id = (String)element.get("id"); - if (relationShapeIds.indexOf(id) != -1 && id.equals(str)) { - String type = element.get("type").toString(); - if ("organization".equals(type)) { - sbOrg.append(","); - sbOrg.append(element.get("text").toString().replace("\n", "")); - continue; - } - if ("position".equals(type) || "role".equals(type)) { - sbRole.append(","); - sbRole.append(element.get("text").toString().replace("\n", "")); - } - } - } - String sbOrgString = specialCharTransfer(sbOrg.toString()); - if (sbOrgString.indexOf(",") == 0) - sbOrgString = sbOrgString.substring(1, sbOrgString.length()); - String sbRoleString = specialCharTransfer(sbRole.toString()); - if (sbRoleString.indexOf(",") == 0) - sbRoleString = sbRoleString.substring(1, sbRoleString.length()); - _tr.put("shape_" + key + "_org", sbOrgString); - _tr.put("shape_" + key + "_role", sbRoleString); } } + if (flag) { + StringBuilder sbOrg = new StringBuilder(_tr.getString("shape_" + key + "_org")); + StringBuilder sbRole = new StringBuilder(_tr.getString("shape_" + key + "_role")); + + for (Map element : relationFileElements) { + String id = (String) element.get("id"); + if (relationShapeIds.indexOf(id) != -1 && id.equals(str)) { + String type = element.get("type").toString(); + if ("organization".equals(type)) { + sbOrg.append(","); + sbOrg.append(element.get("text").toString().replace("\n", "")); + } else if ("position".equals(type) || "role".equals(type)) { + sbRole.append(","); + sbRole.append(element.get("text").toString().replace("\n", "")); + } + } + } + String sbOrgString = specialCharTransfer(sbOrg.toString()); + if (sbOrgString.indexOf(",") == 0) { + sbOrgString = sbOrgString.substring(1, sbOrgString.length()); + } + String sbRoleString = specialCharTransfer(sbRole.toString()); + if (sbRoleString.indexOf(",") == 0) { + sbRoleString = sbRoleString.substring(1, sbRoleString.length()); + } + _tr.put("shape_" + key + "_org", sbOrgString); + _tr.put("shape_" + key + "_role", sbRoleString); + } + } } } } } + /** + * 将图形元素关联属性的id替换为name + * com.alibaba.fastjson + * + * @param key + * @param dataAttribute 图形元素所有关联属性 + * @param shapeRelationModelMap + * @return + */ @Deprecated public static void setShapeValue2(JSONObject _tr, JSONObject dataAttribute, Map shapeRelationModelMap) { String result = ""; String key = dataAttribute.getString("key"); if ("string".equals(dataAttribute.getString("type")) || "textarea".equals(dataAttribute.getString("type"))) { - result = specialCharTransfer(dataAttribute.getString("value")).replace("\n", ""); + result = specialCharTransfer(dataAttribute.getString("value")).replace("\n", OutputWordUtil.WRAPSTRING); } else if ("awsorg".equals(dataAttribute.getString("type"))) { StringBuilder keyValue = new StringBuilder(); if (key != null) { @@ -2073,97 +2759,121 @@ public class OutputWordUtil { String text = shapeRelationModelMap.get(keyId); JSONObject object = JSONObject.parseObject(text); String type = object.getString("type"); - if ("department".equals(type)) { + if ("department".equals(type)) {// 部门 DepartmentModel deptModel = SDK.getORGAPI().getDepartmentById(keyId); - if (deptModel != null) + if (deptModel != null) { keyValue.append(specialCharTransfer(deptModel.getName())).append(","); + } } - if ("user".equals(type)) { + if ("user".equals(type)) {// 人员 UserModel userModel = SDK.getORGAPI().getUser(keyId); - if (userModel != null) + if (userModel != null) { keyValue.append(specialCharTransfer(userModel.getUserName())).append(","); + } } - if ("role".equals(type)) { + if ("role".equals(type)) {// 角色 RoleModel roleModel = SDK.getORGAPI().getRoleById(keyId); - if (roleModel != null) + if (roleModel != null) { keyValue.append(specialCharTransfer(roleModel.getName())).append(","); + } } } } } } - if (keyValue.length() > 0) + if (keyValue.length() > 0) { result = keyValue.toString().substring(0, keyValue.length() - 1); + } } else if ("select".equals(dataAttribute.getString("type"))) { result = specialCharTransfer(dataAttribute.getString("value")); } else { StringBuilder keyValue = new StringBuilder(); - List keyValueList = new ArrayList<>(); + List keyValueList = new ArrayList(); if (key != null) { String attributeValue = dataAttribute.getString("value"); if (attributeValue != null && attributeValue.length() != 0) { attributeValue = attributeValue.replace("[", "").replace("]", "").replace("\"", ""); String[] keyValues = removeRepeat(attributeValue, ",").split(","); for (String keyId : keyValues) { - if (!"".equals(keyId) && shapeRelationModelMap.containsKey(keyId)) + if (!"".equals(keyId) && shapeRelationModelMap.containsKey(keyId)) { keyValueList.add(shapeRelationModelMap.get(keyId)); + } } for (String value : keyValueList) { value = specialCharTransfer(value); keyValue.append(value + ","); } - if (keyValue.length() > 0) + + if (keyValue.length() > 0) { result = keyValue.toString().substring(0, keyValue.length() - 1); + } } } } - _tr.put("shape_" + key, result.replace("\n", "")); + + _tr.put("shape_" + key, result.replace("\n", OutputWordUtil.WRAPSTRING)); } + /** + * 导出word时对特殊字符转义,防止office解析特殊字符打不开 + * 特殊字符"&" "<" ">" + * + * @param str + */ public static String specialCharTransfer(String str) { - if (str == null || "".equals(str.trim())) + if (str == null || "".equals(str.trim())) { return str; + } return str.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">"); } + //排序 private static class ComparatorMap implements Comparator> { - private ComparatorMap() {} - + @Override public int compare(Map json1, Map json2) { - String number1 = OutputWordUtil.getNum(json1); - String number2 = OutputWordUtil.getNum(json2); - if (!OutputUtil.isPositiveInteger(number1) || !OutputUtil.isPositiveInteger(number2)) + String number1 = getNum(json1); + String number2 = getNum(json2); + if (!OutputUtil.isPositiveInteger(number1) || !OutputUtil.isPositiveInteger(number2)) { return number1.compareTo(number2); - Integer n1 = Integer.valueOf(0); - Integer n2 = Integer.valueOf(0); - n1 = Integer.valueOf(Integer.parseInt(number1)); - n2 = Integer.valueOf(Integer.parseInt(number2)); - return n1.compareTo(n2); + } else { + Integer n1 = 0; + Integer n2 = 0; + n1 = Integer.parseInt(number1); + n2 = Integer.parseInt(number2); + return n1.compareTo(n2); + } } + } private static String getNum(Map json) { - if (json.containsKey("number")) + if (json.containsKey("number")) { return json.get("number").toString(); + } if (json.containsKey("attributes")) { - if (json.get("attributes") instanceof JSONObject) { - JSONObject dataJson = (JSONObject)json.get("attributes"); - if (dataJson.containsKey("privateAttributeContent") && dataJson.get("privateAttributeContent").getClass().getName().contains("JSONObject")) + if (json.get("attributes") instanceof JSONObject) {// netJson + JSONObject dataJson = (JSONObject) json.get("attributes"); + if (dataJson.containsKey("privateAttributeContent") && dataJson.get("privateAttributeContent").getClass().getName().contains("JSONObject")) { return dataJson.getJSONObject("privateAttributeContent").getString("number"); + } } - if (json.get("attributes") instanceof JSONObject) { - JSONObject dataJson = (JSONObject)json.get("attributes"); - if (dataJson.containsKey("privateAttributeContent") && dataJson.get("privateAttributeContent").getClass().getName().contains("JSONObject")) + if (json.get("attributes") instanceof JSONObject) {// fastJson + JSONObject dataJson = (JSONObject) json.get("attributes"); + if (dataJson.containsKey("privateAttributeContent") && dataJson.get("privateAttributeContent").getClass().getName().contains("JSONObject")) { return dataJson.getJSONObject("privateAttributeContent").getString("number"); + } } if (json.get("attributes") instanceof JSONArray) { - JSONArray dataJson = (JSONArray)json.get("attributes"); + JSONArray dataJson = (JSONArray) json.get("attributes"); for (int i = 0; i < dataJson.size(); i++) { - JSONObject obj = (JSONObject)dataJson.get(i); - if ("number".equals(obj.getString("key"))) + JSONObject obj = (JSONObject) dataJson.get(i); + if ("number".equals(obj.getString("key"))) { return obj.getString("value"); - if (obj.getString("key") != null && obj.getString("key").contains("number")) + } + //加入活动序号排序处理 + if (obj.getString("key") != null && obj.getString("key").contains("number")) { return obj.getString("value"); + } } } } @@ -2172,11 +2882,17 @@ public class OutputWordUtil { public static void orderByNumber(List> list) { ComparatorMap comparator = new ComparatorMap(); - if (list != null && list.size() > 0) + + if (list != null && list.size() > 0) { Collections.sort(list, comparator); + } } + + + + public static JSONArray getVersionHistoryTable(PALRepositoryModel repositoryModel) { JSONArray versionHistoryTable = new JSONArray();// 修订记录 List list = PALRepositoryCache.getByVersionId(repositoryModel.getVersionId()); @@ -2243,111 +2959,153 @@ public class OutputWordUtil { return versionHistoryTable; } - + /** + * xml转换成word(找doc文件,执行转换) + * @param log + * @param fileDirPath + */ public static void xml2Word(GenerLogExd log, String fileDirPath) { File dir = new File(fileDirPath); if (dir.exists() && dir.isDirectory()) { - File[] files = dir.listFiles(); + File [] files = dir.listFiles(); for (int i = 0; i < files.length; i++) { File file = files[i]; - if (file.isFile() && file.getName().toLowerCase().endsWith(".doc")) + if (file.isFile() && file.getName().toLowerCase().endsWith(".doc")) { xml2Word(log, fileDirPath, file.getName()); + } } } } + /** + * xml转换成word + * @param filePath + * @param fileName + */ public static void xml2Word(GenerLogExd log, String filePath, String fileName) { - boolean record = (log != null); + boolean record = log != null; File file = new File(filePath, fileName); if (file.exists() && isXML(file.getPath())) { Document document = new Document(); document.loadFromFile(file.getPath()); document.saveToFile(file.getPath(), FileFormat.Doc); - if (record) + if (record) { log.info("文件从XML格式转换成Doc格式"); - } else if (record) { - log.info("文件不存在或者文件不是XML格式,无需转换成Doc格式"); + } + } else { + if (record) { + log.info("文件不存在或者文件不是XML格式,无需转换成Doc格式"); + } } } public static boolean isXML(String filePath) { try (FileInputStream fis = new FileInputStream(filePath)) { - byte[] buffer = new byte[50]; + byte[] buffer = new byte[50]; // 假设我们读取前50个字节进行检测 int bytesRead = fis.read(buffer); String startOfFile = new String(buffer, 0, bytesRead, StandardCharsets.UTF_8); + + // 使用正则表达式来处理可能出现的前导空白字符 return startOfFile.trim().startsWith(" headers = WPS4Util.getSignatureHeaders(url, "POST", result.toString(), "application/json"); - JSONObject json = (JSONObject)HttpPostUtil.sendPostRequest(YiliWpsConst.HOST + "/open" + url, result.toString(), headers, JSONObject.class); + //组装完毕 + Map headers = WPS4Util.getSignatureHeaders(url, "POST",result.toString(), YiliWpsConst.CONTENT_TYPE); + JSONObject json = HttpPostUtil.sendPostRequest(YiliWpsConst.HOST + "/open" + url, result.toString(), headers, JSONObject.class); System.out.println("jsonObject = " + json.toString()); - if (json.getString("code").equals("200")) { + if(json.getString("code").equals("200")){ System.out.println(">>>>>>>已合并成功"); String download_id = json.getJSONObject("data").getString("download_id"); String route_key = json.getJSONObject("data").getString("route_key"); + //String savePath = AWSPortalConf.getUrl() +"/test/123.doc"; + //patc和name中间不需要加"/"杠,兼容有斜杠的场景 + //String savePath = dc.getPath()+"/"+dc.getFileName(); String savePath = ""; - if (dc.getPath().endsWith("/")) { - savePath = dc.getPath() + dc.getFileName(); - } else { - savePath = dc.getPath() + "/" + dc.getFileName(); + if(dc.getPath().endsWith("/")){ + savePath = dc.getPath()+dc.getFileName(); + }else{ + savePath = dc.getPath()+"/"+dc.getFileName(); } System.out.println("savePath = " + savePath); - operateDocumentResultDownload(YiliWpsConst.HOST, download_id, route_key, savePath); + operateDocumentResultDownload(YiliWpsConst.HOST,download_id,route_key,savePath); return savePath; } return ""; - } catch (Exception e) { + }catch (Exception e){ e.printStackTrace(); - return ""; } + return ""; } - public static void operateDocumentResultDownload(String host, String downloadId, String routeKey, String savePath) throws Exception { + /** + * 根据wps的下载id下载替换文件 + * @param host + * @param downloadId + * @param routeKey + * @param savePath + * @throws Exception + */ + public static void operateDocumentResultDownload(String host,String downloadId,String routeKey,String savePath) throws Exception { String url = "/api/cps/v1/download/{download_id}"; - url = url.replace("{download_id}", downloadId); - Map headers = WPS4Util.getSignatureHeaders(url, "GET", null, "application/json"); - headers.put("Route-Key", routeKey); - HttpPostUtil.sendGetDownloadRequest(host + "/open" + url, headers, savePath); + url = url.replace("{download_id}",downloadId); + Map headers = WPS4Util.getSignatureHeaders(url, "GET",null,YiliWpsConst.CONTENT_TYPE); + headers.put("Route-Key",routeKey); + HttpPostUtil.sendGetDownloadRequest(host + "/open" + url, headers,savePath); } - public static void downloadFile(String fileURL, String saveDir, String fileName) { + public static void downloadFile(String fileURL, String saveDir,String fileName) { try { File file = new File(saveDir); - if (!file.exists()) + + // 确保文件目录存在 + if (!file.exists()) { file.mkdirs(); + } + // 创建输出流到文件 File outputFile = new File(file, fileName); FileOutputStream fos = new FileOutputStream(outputFile); URL url = new URL(fileURL); - HttpURLConnection httpConn = (HttpURLConnection)url.openConnection(); + HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); int responseCode = httpConn.getResponseCode(); - if (responseCode == 200) { + // 检查响应码是否为HTTP_OK + if (responseCode == HttpURLConnection.HTTP_OK) { + // 通过输入流读取数据 InputStream inputStream = httpConn.getInputStream(); byte[] buffer = new byte[4096]; int bytesRead = -1; - while ((bytesRead = inputStream.read(buffer)) != -1) + + while ((bytesRead = inputStream.read(buffer)) != -1) { fos.write(buffer, 0, bytesRead); + } + fos.close(); inputStream.close(); + System.out.println("File downloaded"); } else { System.out.println("No file to download. Server replied HTTP code: " + responseCode); @@ -2360,24 +3118,281 @@ public class OutputWordUtil { public static void sortFilesByNumber(List fileList) { fileList.sort( - Comparator.comparing(OutputWordUtil::extractLeadingNumber, - - Comparator.nullsLast(Comparator.naturalOrder()))); + Comparator.comparing( + OutputWordUtil::extractLeadingNumber, + Comparator.nullsLast(Comparator.naturalOrder()) + ) + ); } - + // 提取附件后的第一个连续数字(支持小数) private static Double extractLeadingNumber(UpfileModel file) { - Pattern FILE_NUMBER_PATTERN = Pattern.compile("^附件[^\\d]*(\\d+(?:\\.\\d+)?|\\.\\d+)"); + Pattern FILE_NUMBER_PATTERN = + Pattern.compile("^附件[^\\d]*(\\d+(?:\\.\\d+)?|\\.\\d+)"); // 增强正则 try { Matcher matcher = FILE_NUMBER_PATTERN.matcher(file.getFileName()); if (matcher.find()) { String numberStr = matcher.group(1); - if (numberStr.endsWith(".")) + // 处理结尾单独的小数点(如"123."的情况) + if (numberStr.endsWith(".")) { numberStr = numberStr.substring(0, numberStr.length() - 1); - return Double.valueOf(Double.parseDouble(numberStr)); + } + return Double.parseDouble(numberStr); } return null; } catch (Exception e) { return null; } } + + /** + * 判断是否需求合并管理要求 + * @param uuid + */ + /** + * 判断是否需求合并管理要求 + * @param uuid + */ + public static void mergeMRWord(String filePath, String uuid,JSONObject dataMap) { + Map stringJSONObjectMap = PALRepositoryQueryAPIManager.queryRepositoryAttributeById(uuid); + JSONObject attrJson = stringJSONObjectMap.get("management_requirements_Location"); + String text = attrJson.getString("text"); + if ("不显示管理要求".equals(text)) { + return; + } + BO mrBO = SDK.getBOAPI().getByKeyField("BO_EU_PROCESS_MR", "FILEUUID", uuid); + if (null == mrBO || !"1".equals(mrBO.getString("STATUS"))) { + return; + } + + List systemfile = SDK.getBOAPI().getFiles(mrBO.getId(), "SYSTEMFILE"); + if (systemfile.isEmpty()) { + return; + } + FormFile formFile = systemfile.get(0); + DCContext fileDCContext = SDK.getBOAPI().getFileDCContext(formFile); + + // 加载目标文件和待合并文档2 + Document docs1 = new Document(); + docs1.loadFromFile(filePath); + Document docs2 = new Document(); + docs2.loadFromFile(fileDCContext.getFilePath()); + + + Section lastSection1 = docs1.getLastSection(); + + // 删除最后一个节 + docs1.getSections().remove(lastSection1); + + + // 定位插入位置:根据text判断是“流程图前”还是“活动说明后(表格后)” + Paragraph targetPara = null; + Section targetSection = null; + int targetParaIndex = -1; + if ("流程图前".equals(text)) { + // 保持原有“流程图前”逻辑(适配文件中“# 2. 流程图”) + for (Object obj : docs1.getSections()) { + Section sec = (Section) obj; + int i = 0; + for (Object parObj : sec.getParagraphs()) { + Paragraph para = (Paragraph) parObj; + if (para.getText().trim().contains("2. 流程图") || para.getText().trim().equals("流程图")) { + targetPara = para; + targetSection = sec; + targetParaIndex = i; + break; + } + i++; + } + if (targetPara != null) { + break; + } + } + + + // 插入文档2内容(保持格式与文件协调) + Section doc2Sec = docs2.getSections().get(0); + boolean isFirstPara = true; + for (Object obj : doc2Sec.getParagraphs()) { + Paragraph doc2Para = (Paragraph) obj; + Paragraph clonedPara = (Paragraph) doc2Para.deepClone(); + ParagraphFormat format = clonedPara.getFormat(); + + // 核心格式:确保同页且不挤压 + format.setPageBreakBefore(false); + format.setPageBreakAfter(false); + format.setKeepLines(true); + format.setKeepFollow(true); + format.setLineSpacingRule(LineSpacingRule.At_Least); + format.setLineSpacing(12f); // 适配文件中行高 + + // 第一段与表格保持6磅间距(避免贴紧表格底部) + if (isFirstPara) { + float beforeSpacing = format.getBeforeSpacing(); + format.setBeforeSpacing(beforeSpacing > 0 ? beforeSpacing : 6f); + isFirstPara = false; + } + + // 插入到目标位置(表格下方) + targetSection.getParagraphs().insert(targetParaIndex, clonedPara); + targetParaIndex++; + } + + // 调整后续段落(如矩阵标题)与插入内容的间距 + ParagraphFormat targetFormat = targetPara.getFormat(); + targetFormat.setBeforeSpacing(6f); // 与插入内容保持6磅间距 + targetFormat.setPageBreakBefore(false); + + // 保存文档 + docs1.saveToFile(filePath, FileFormat.Docx_2013); + docs1.dispose(); + docs2.dispose(); + + + } else if ("活动说明后".equals(text)) { + + + boolean processDescriptionFound = false; + boolean tableFoundAfterDescription = false; + for (Object obj : docs1.getSections()) { + Section sec = (Section) obj; + int i = 0; + for (Object paragraph : sec.getParagraphs()) { + Paragraph para = (Paragraph)paragraph; + String paraText = para.getText().trim(); + if (paraText.contains("3. 流程说明") || paraText.contains("流程说明")) { + processDescriptionFound = true; + tableFoundAfterDescription = false; + continue; + } + if (processDescriptionFound) { + boolean tableFound = false; + Iterator

iterator = sec.getTables().iterator(); + if (iterator.hasNext()) { + Table table = iterator.next(); + tableFoundAfterDescription = true; + targetPara = sec.addParagraph(); + targetParaIndex = i + 2; + targetSection = sec; + } + if (tableFoundAfterDescription) + break; + } + i++; + } + if (targetPara != null) + break; + } + + + // 在目标文档末尾添加分节符,确保新节可以有不同的页面设置 + Section lastSection=docs1.addSection(); + + //设置页面方向为竖向 + lastSection.getPageSetup().setOrientation(PageOrientation.Portrait); + + //设置页面页眉页脚不连续 + lastSection.getHeadersFooters().setLinkToPrevious(false); // 关键步骤! + + + //获取该节的页眉,移除其中的内容,然后在其中添加一个空白段落 + // 克隆源文档的所有节内容到目标文档的最后一节 + for (Object sectionObj : docs2.getSections()) { + Section sourceSection = (Section) sectionObj; + for (Object docObj2 : sourceSection.getParagraphs()) { + Paragraph doc2Para = (Paragraph) docObj2; + Paragraph clonedPara = (Paragraph) doc2Para.deepClone(); + // 将克隆的内容添加到目标文档的最后一节 + lastSection.getBody().getChildObjects().add(clonedPara); + + + + //添加页眉 + HeaderFooter targetHeader = lastSection.getHeadersFooters().getHeader(); + targetHeader.getChildObjects().clear(); + + HeaderFooter header = lastSection.getHeadersFooters().getHeader(); + Paragraph hpara= header.addParagraph(); + + // 先添加文字到页眉左侧 + TextRange txt = hpara.appendText(dataMap.getString("HEADERFONT")); + txt.getCharacterFormat().setUnderlineStyle(UnderlineStyle.None); + txt.getCharacterFormat().setFontSize(10f); + txt.getCharacterFormat().setFontName("黑体"); + + + + // 添加制表符以实现右侧定位 + hpara.appendText("\t"); + + // 添加图片到页眉右侧 + DocPicture pic = hpara.appendPicture(dataMap.getString("LOGOURL")); + pic.setHorizontalAlignment(ShapeHorizontalAlignment.Right); + pic.setVerticalOrigin(VerticalOrigin.Top_Margin_Area); + pic.setVerticalAlignment(ShapeVerticalAlignment.Center); + pic.setWidth(44.0F); + pic.setHeight(35.0F); + // 设置段落格式:左侧文字左对齐,右侧图片右对齐 + hpara.getFormat().setHorizontalAlignment(HorizontalAlignment.Left); + hpara.getFormat().setLeftIndent(0f); + hpara.getFormat().setFirstLineIndent(0f); + hpara.getFormat().setBeforeSpacing(0f); // 也可以调整段前间距 + + + // 设置制表位以实现右侧定位 + Tab tab = hpara.getFormat().getTabs().addTab(500f, TabJustification.Right, TabLeader.No_Leader); + + + // 设置图片的文本环绕方式 + pic.setTextWrappingStyle(TextWrappingStyle.Behind); + + // 设置页眉底部边线(粗细、间距)- 文字和图片都在横线上面 + hpara.getFormat().getBorders().getBottom().setBorderType(BorderStyle.Single); + hpara.getFormat().getBorders().getBottom().setLineWidth(0.5f); + hpara.getFormat().getBorders().setSpace(10f); + + + + + + //页脚操作 + HeaderFooter targetFooter = lastSection.getHeadersFooters().getFooter(); + targetFooter.getChildObjects().clear(); + + HeaderFooter footer = lastSection.getHeadersFooters().getFooter(); + Paragraph fpara= footer.addParagraph(); + + // 先添加文字到页脚左侧 + TextRange foottxt = fpara.appendText(dataMap.getString("FOOTERFONT")); + foottxt.getCharacterFormat().setUnderlineStyle(UnderlineStyle.None); + foottxt.getCharacterFormat().setFontSize(10f); + foottxt.getCharacterFormat().setFontName("黑体"); + + + fpara.getFormat().getBorders().getTop().setBorderType(BorderStyle.Single); + fpara.getFormat().getBorders().getTop().setLineWidth(1f); + + + // 调整页脚段落的间距,确保横线在文字上方有适当距离 + // 增加段前间距来将横线向下移动 + fpara.getFormat().setBeforeSpacing(1500f); // 增加段前间距,将横线向下推 + fpara.getFormat().setAfterSpacing(0f); // 段后间距 + + // 设置页脚文字左对齐 + fpara.getFormat().setHorizontalAlignment(HorizontalAlignment.Left); + + // 调整页脚段落的间距,确保横线在文字上方有适当距离 + + } + + } + // 保存文档 + docs1.saveToFile(filePath, FileFormat.Docx_2013); + docs1.dispose(); + docs2.dispose(); + + } + + } + + }