package com.ots.common.utils.poi; import cn.hutool.core.collection.CollUtil; import com.ots.common.enums.ReportTypeNameEnum; import com.ots.common.enums.TemplateTypeEnum; import com.ots.common.utils.StringUtils; import com.ots.framework.config.EssConfig; import com.ots.framework.web.domain.AjaxResult; import com.ots.project.exam.domain.TReportTemplate; import com.ots.project.exam.dto.JAQTableStyle; import com.ots.project.exam.dto.WordParam; import com.ots.project.tool.ShellTool; import com.ots.project.tool.exam.ExamUtil; import com.ots.project.tool.exam.ImageUtil; import com.ots.project.tool.exam.ZipUtil; import com.ots.project.tool.report.JAQ.condition.Table1; import com.ots.project.tool.report.JAQ.condition.Table2; import com.ots.project.tool.report.JAQ.condition.Table3; import com.ots.project.tool.report.JAQ.condition.Table4; import org.apache.commons.collections.map.HashedMap; import org.apache.poi.ooxml.POIXMLDocument; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.util.Units; import org.apache.poi.xwpf.usermodel.Document; import org.apache.poi.xwpf.usermodel.IBodyElement; import org.apache.poi.xwpf.usermodel.IRunElement; import org.apache.poi.xwpf.usermodel.XWPFChart; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFHeader; import org.apache.poi.xwpf.usermodel.XWPFParagraph; import org.apache.poi.xwpf.usermodel.XWPFRun; import org.apache.poi.xwpf.usermodel.XWPFTable; import org.apache.poi.xwpf.usermodel.XWPFTableCell; import org.apache.poi.xwpf.usermodel.XWPFTableRow; import org.apache.xmlbeans.XmlCursor; import org.apache.xmlbeans.XmlException; import org.jetbrains.annotations.Nullable; import org.openxmlformats.schemas.drawingml.x2006.chart.CTAxDataSource; import org.openxmlformats.schemas.drawingml.x2006.chart.CTBarChart; import org.openxmlformats.schemas.drawingml.x2006.chart.CTBarSer; import org.openxmlformats.schemas.drawingml.x2006.chart.CTChart; import org.openxmlformats.schemas.drawingml.x2006.chart.CTNumDataSource; import org.openxmlformats.schemas.drawingml.x2006.chart.CTNumVal; import org.openxmlformats.schemas.drawingml.x2006.chart.CTPlotArea; import org.openxmlformats.schemas.drawingml.x2006.chart.CTScatterChart; import org.openxmlformats.schemas.drawingml.x2006.chart.CTScatterSer; import org.openxmlformats.schemas.drawingml.x2006.main.CTGraphicalObject; import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTAnchor; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTDrawing; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPPr; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.awt.image.BufferedImage; 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.OutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; public class WordUtil { private static final Logger log = LoggerFactory.getLogger(WordUtil.class); public static String tempFilePath = "/Users/shawnli/Downloads/"; private static String noRunChange = ""; public static final int DEFAULT_FONT_SIZE = 10; public static boolean changWord(String inputUrl, String outputUrl, Map textMap, Map tableMap) { try { XWPFDocument document = new XWPFDocument(POIXMLDocument.openPackage(inputUrl)); WordUtil.changeText(document, textMap); WordUtil.changeTable(document, textMap); File file = new File(outputUrl); FileOutputStream stream = new FileOutputStream(file); document.write(stream); stream.close(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return true; } public static OutputStream getReportWord(String inputUrl, String outputUrl, Map textMap, Map tableMap) { try { XWPFDocument document = new XWPFDocument(POIXMLDocument.openPackage(inputUrl)); WordUtil.changeText(document, textMap); WordUtil.changeTable(document, textMap); File file = new File(outputUrl); return new FileOutputStream(file); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return null; } public static boolean changWord(String inputUrl, String outputUrl, Map textMap, WordParam wordParam) { boolean changeFlag = true; try { XWPFDocument document = new XWPFDocument(POIXMLDocument.openPackage(inputUrl)); WordUtil.changeText(document, textMap); File file = new File(outputUrl); FileOutputStream stream = new FileOutputStream(file); document.write(stream); stream.close(); } catch (IOException e) { e.printStackTrace(); changeFlag = false; } catch (Exception e) { } return changeFlag; } public static void changeText(XWPFDocument document, Map textMap) throws IOException, InvalidFormatException { setHeader(document, textMap); List elements = document.getBodyElements(); List paragraphs = new ArrayList<>(); for (IBodyElement iBodyElement : elements) { if (iBodyElement instanceof XWPFParagraph) { paragraphs.add((XWPFParagraph) iBodyElement); } } for (XWPFParagraph paragraph : paragraphs) { String text = paragraph.getText(); if (checkText(text)) { List iRunElements = paragraph.getIRuns(); List runs = new ArrayList<>(); for (IRunElement iRunElement : iRunElements) { runs.add((XWPFRun) iRunElement); } int runPosition = 0; for (XWPFRun run : runs) { String changeValueStr = changeValue(run.toString(), textMap, run, paragraph, document, runPosition); if (!StringUtils.equals(changeValueStr, "NoChangValue")) { run.setText(changeValueStr, 0); } runPosition++; } } } } private static void setHeader(XWPFDocument document, Map textMap) { try { List headerList = document.getHeaderList(); for (XWPFHeader header : headerList) { List paragraphs = header.getParagraphs(); setHeadTable(document, textMap, header); setHeadParagraph(textMap, paragraphs); } } catch (Exception e) { log.info("正常的异常,没有表头数据{}", e.getMessage(), e); } } private static void setHeadParagraph(Map textMap, List paragraphs) { for (XWPFParagraph xwpfParagraph : paragraphs) { List runs = xwpfParagraph.getRuns(); for (XWPFRun run : runs) { log.info(run.toString()); if (run.toString().indexOf("%TName%") != -1) { run.setText(textMap.get("questionnaireTaker").toString(), 0); } if (run.toString().indexOf("%TTime%") != -1) { run.setText(textMap.get("reportGenerationDate").toString(), 0); } } } } private static void setHeadTable(XWPFDocument document, Map textMap, XWPFHeader header) { if (Objects.nonNull(textMap.get("questionnaireTaker"))) { textMap.put("TName", textMap.get("questionnaireTaker").toString()); } if (Objects.nonNull(textMap.get("reportGenerationDate"))) { textMap.put("TTime", textMap.get("reportGenerationDate").toString()); } List tables = header.getTables(); if (CollUtil.isEmpty(tables)) { return; } setTableValue(document, textMap, tables); } public static void changePage(XWPFDocument document) throws IOException, org.apache.poi.openxml4j.exceptions.InvalidFormatException { List paragraphs = document.getParagraphs(); for (XWPFParagraph paragraph : paragraphs) { String text = paragraph.getText(); if (text.indexOf("%page-change%") != -1) { List runs = paragraph.getRuns(); for (XWPFRun run : runs) { if (StringUtils.equals(run.toString(), "%page-change%")) { run.setText("", 0); } } paragraph.getCTP().getPPr().addNewSectPr(); } } } public static void changeLine(XWPFDocument document) throws IOException, org.apache.poi.openxml4j.exceptions.InvalidFormatException { List paragraphs = document.getParagraphs(); for (XWPFParagraph paragraph : paragraphs) { String text = paragraph.getText(); if (text.indexOf("%line-feed%") != -1) { List runs = paragraph.getRuns(); for (XWPFRun run : runs) { if (StringUtils.equals(run.toString(), "%line-feed%")) { run.setText("", 0); run.addBreak(); } } } } } private static void setPicture(XWPFRun run, WordParam wordParam) throws org.apache.poi.openxml4j.exceptions.InvalidFormatException, IOException { InputStream in = new FileInputStream(wordParam.getContent()); BufferedImage bufferedImage = ImageUtil.getImage(wordParam.getContent()); int width = (int) Math.round(bufferedImage.getWidth()); int height = (int) Math.round(bufferedImage.getHeight()); int emuSelf = 3000; run.addPicture(in, Document.PICTURE_TYPE_PNG, "TEST", width * emuSelf, height * emuSelf); in.close(); if (wordParam.isMove()) { CTDrawing drawing = run.getCTR().getDrawingArray(0); CTGraphicalObject graphicalobject = drawing.getInlineArray(0).getGraphic(); CTAnchor anchor = getAnchorWithGraphic(graphicalobject, "TEST1", Units.toEMU(wordParam.getPicWidth()), Units.toEMU(wordParam.getPicHeight()), Units.toEMU(wordParam.getX()), Units.toEMU(wordParam.getY()), false, wordParam.getTopPosition()); drawing.setAnchorArray(new CTAnchor[]{anchor}); drawing.removeInline(0); } } public static CTAnchor getAnchorWithGraphic(CTGraphicalObject ctGraphicalObject, String deskFileName, int width, int height, int leftOffset, int topOffset, boolean behind, int topPosition) { long relativeHeight = 251649024l + topPosition; String anchorXML = "" + "" + "" + "" + leftOffset + "" + "" + "" + "" + topOffset + "" + "" + "" + "" + "" + "" + ""; CTDrawing drawing = null; try { drawing = CTDrawing.Factory.parse(anchorXML); } catch (XmlException e) { e.printStackTrace(); } CTAnchor anchor = drawing.getAnchorArray(0); anchor.setGraphic(ctGraphicalObject); return anchor; } public static void changeTable(XWPFDocument document, Map textMap) { List tables = document.getTables(); setTableValue(document, textMap, tables); } private static void setTableValue(XWPFDocument document, Map textMap, List tables) { for (int i = 0; i < tables.size(); i++) { log.info("第" + (i + 1) + "个表:"); try { XWPFTable table = tables.get(i); if (table.getRows().size() > 0) { log.info("表格数据:"+ table.getText()); if (checkText(table.getText())) { List rows = table.getRows(); eachTable(rows, textMap, document); } } } catch (Exception e) { log.info("表格发生了多行!"); } } } private static void addTableValue(XWPFDocument document, Map>> autoTableMap) { if (Objects.isNull(autoTableMap)) { return; } List tables = document.getTables(); for (int i = 0; i < tables.size(); i++) { log.info("第" + (i + 1) + "个表:"); try { XWPFTable table = tables.get(i); if (table.getRows().size() > 0) { log.info("添加行表格数据:" + table.getText()); Map> mapRowsMap = autoTableMap.get(i); log.info("插入" + table.getText()); insertTable(table, mapRowsMap.get(i), 1); } } catch (Exception e) { log.info("表格发生了多行!"); } } } private static void setTableMap(Map tableMap, Map> mapRowsMap) { if (Objects.isNull(tableMap) || tableMap.isEmpty()) { return; } List table1 = (List) tableMap.get("table1"); List table1List = new ArrayList<>(); for (Table1 t : table1) { table1List.add(t.toRow()); } mapRowsMap.put(0, table1List); List table2 = (List) tableMap.get("table2"); List table2List = new ArrayList<>(); for (Table2 t : table2) { table2List.add(t.toRow()); } mapRowsMap.put(1, table2List); List table3 = (List) tableMap.get("table3"); List table3List = new ArrayList<>(); for (Table3 t : table3) { table3List.add(t.toRow()); } mapRowsMap.put(2, table3List); List table4 = (List) tableMap.get("table4"); List table4List = new ArrayList<>(); for (Table4 t : table4) { table4List.add(t.toRow()); } mapRowsMap.put(3, table4List); } public static void eachTable(List rows, Map textMap, XWPFDocument document) throws IOException, org.apache.poi.openxml4j.exceptions.InvalidFormatException { for (XWPFTableRow row : rows) { List cells = row.getTableCells(); for (XWPFTableCell cell : cells) { if (checkText(cell.getText())) { List paragraphs = cell.getParagraphs(); for (XWPFParagraph paragraph : paragraphs) { List iRunElements = paragraph.getIRuns(); List runs = new ArrayList<>(); for (IRunElement iRunElement : iRunElements) { runs.add((XWPFRun) iRunElement); } int runPosition = 0; for (XWPFRun run : runs) { setTextValue(textMap, document, paragraph, runPosition, run); } } } } } } private static void setTextValue(Map textMap, XWPFDocument document, XWPFParagraph paragraph, int runPosition, XWPFRun run) { System.out.println("表格的:" + run.toString()); try { run.setText(changeValue(run.toString(), textMap, run, paragraph, document, runPosition), 0); } catch (Exception e) { } } public static void insertTable(XWPFTable table, List tableList, int inserRowNum) { for (int i = 0; i < tableList.size(); i++) { XWPFTableRow row = table.createRow(); } XWPFTableRow headXwpfTableRow = table.getRows().get(0); for (int i = inserRowNum; i <= tableList.size(); i++) { XWPFTableRow newRow = table.getRow(i); List cells = newRow.getTableCells(); for (int j = 0; j < cells.size(); j++) { try { XWPFTableCell cell = cells.get(j); cell.setText(tableList.get(i - 1)[j]); cell.getParagraphs().get(0).getCTP().setPPr(headXwpfTableRow.getCell(0).getParagraphs().get(0).getCTP().getPPr()); } catch (Exception e) { } } } } public static boolean checkText(String text) { if (text.indexOf("%") != -1 || StringUtils.equals(text, "N/A NONE")) { return true; } return false; } public static String changeValue(String runValue, Map textMap, XWPFRun run, XWPFParagraph paragraph, XWPFDocument document, int runPosition) throws IOException, org.apache.poi.openxml4j.exceptions.InvalidFormatException { Set> textSets = textMap.entrySet(); for (Map.Entry textSet : textSets) { String key = "%" + textSet.getKey() + "%"; if (runValue.indexOf("%page-change%") != -1) { runValue = ""; paragraph.getCTP().getPPr().addNewSectPr(); break; } else if (runValue.indexOf("%line-feed%") != -1) { runValue = ""; run.addBreak(); break; } else if (runValue.indexOf(key) != -1) { runValue = changeWordAndPicValue(runValue, run, textSet, key, paragraph, document); if (runValue.indexOf("") != -1) { return setOtherStyle(runValue, paragraph, runPosition, run); } break; } } if (checkText(runValue)) { runValue = runValue.replaceAll("%.*%", ""); runValue = runValue.replaceAll("N/A NONE", ""); } return runValue; } private static String setOtherStyle(String runValue, XWPFParagraph paragraph, int runPosition, XWPFRun oldRun) { int position = 0; int pointer = 0; int end = runValue.length(); List stringList = new ArrayList<>(); while (pointer < end) { position = runValue.indexOf("", pointer); if (position != -1) { String originalRunStr = runValue.substring(pointer, position); if (StringUtils.isNotEmpty(originalRunStr)) { stringList.add(originalRunStr); XWPFRun insertRun = paragraph.insertNewRun(runPosition++); insertRun.setText(originalRunStr); insertRun.setBold(oldRun.isBold()); insertRun.setColor(oldRun.getColor()); int fontSize = oldRun.getFontSize(); insertRun.setFontSize((fontSize == -1) ? DEFAULT_FONT_SIZE : fontSize); } pointer = position; position = runValue.indexOf("", pointer); position += 11; String newRunStr = runValue.substring(pointer, position); if (StringUtils.isNotEmpty(newRunStr)) { newRunStr = newRunStr.replaceAll("", ""); newRunStr = newRunStr.replaceAll("", ""); stringList.add(newRunStr); XWPFRun insertRun = paragraph.insertNewRun(runPosition++); insertRun.setText(newRunStr); insertRun.setBold(true); insertRun.setColor(oldRun.getColor()); int fontSize = oldRun.getFontSize(); insertRun.setFontSize((fontSize == -1) ? DEFAULT_FONT_SIZE : fontSize); } pointer = position; } else { stringList.add(runValue.substring(pointer, end)); XWPFRun insertRun = paragraph.insertNewRun(runPosition++); insertRun.setText(runValue.substring(pointer, end)); insertRun.setBold(oldRun.isBold()); insertRun.setColor(oldRun.getColor()); int fontSize = oldRun.getFontSize(); insertRun.setFontSize((fontSize == -1) ? DEFAULT_FONT_SIZE : fontSize); pointer = end; } } paragraph.removeRun(runPosition); return "NoChangValue"; } private static void changOtherPicture(XWPFParagraph paragraph) { String paragraphText = paragraph.getText(); if (paragraphText.indexOf("{start.png}") == -1) { return; } List iRunElements = paragraph.getIRuns(); XWPFRun oldRun = (XWPFRun) iRunElements.get(0); int position = 0; int poiter = 0; int end = paragraphText.length(); int starLength = "{start.png}".length(); int runPosition = 0; while (position < end) { position = paragraphText.indexOf("{start.png}", position); String value = ""; if (position == -1) { runPosition = insertPicRun(paragraph, oldRun, runPosition, paragraphText.substring(poiter, end)); break; } if (poiter == position) { position = position + starLength; runPosition = insertSmallRunPic(paragraph, runPosition); poiter = position; continue; } else { runPosition = insertPicRun(paragraph, oldRun, runPosition, paragraphText.substring(poiter, position)); poiter = position; position = poiter + starLength; runPosition = insertSmallRunPic(paragraph, runPosition); poiter = position; } } for (int i = runPosition; i < iRunElements.size(); i++) { paragraph.removeRun(i); } } private static int insertSmallRunPic(XWPFParagraph paragraph, int runPosition) { XWPFRun insertRun = paragraph.insertNewRun(runPosition++); WordParam wordParam = new WordParam(); wordParam.setPicHeight(1); wordParam.setPicWidth(1); wordParam.setMove(false); wordParam.setContent(EssConfig.getReportTemplates() + "start.png"); try { setPicture(insertRun, wordParam); } catch (InvalidFormatException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return runPosition; } private static int insertPicRun(XWPFParagraph paragraph, XWPFRun oldRun, int runPosition, String value) { XWPFRun insertRun = paragraph.insertNewRun(runPosition++); insertRun.setText(value); insertRun.setBold(oldRun.isBold()); insertRun.setColor(oldRun.getColor()); int fontSize = oldRun.getFontSize(); insertRun.setFontSize((fontSize == -1) ? DEFAULT_FONT_SIZE : fontSize); return runPosition; } private static String changeWordAndPicValue(String runValue, XWPFRun run, Map.Entry textSet, String key, XWPFParagraph paragraph, XWPFDocument document) throws org.apache.poi.openxml4j.exceptions.InvalidFormatException, IOException { if (textSet.getValue() instanceof WordParam) { setPicture(run, (WordParam) textSet.getValue()); } else { String keyTemp = textSet.getKey(); String keyValue = Objects.isNull(textSet.getValue()) ? "" : textSet.getValue().toString(); if (StringUtils.contains(keyValue, "%line-feed%")) { String[] keyValues = keyValue.split("%line-feed%"); runValue = delDynList(keyTemp, Arrays.asList(keyValues), paragraph, document); } log.info("ChangeValue的key值:" + key + " ChangeValue的value值:" + keyValue); runValue = runValue.replaceAll(key, keyValue); } return runValue; } public AjaxResult exportBaseOrDetailReport(String fileName, List deleteFileStrList, List fileNameList) { try { zipWord(fileName, fileNameList); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } deleteFileByStr(deleteFileStrList); return AjaxResult.success(fileName + ".zip"); } public AjaxResult exportZipKeepFiles(String fileName, List deleteFileStrList, List fileNameList) throws FileNotFoundException { zipKeepWord(fileName, fileNameList); deleteFileByStr(deleteFileStrList); return AjaxResult.success(fileName + ".zip"); } public static String makeReportFile(String fileName, TReportTemplate tReportTemplate, Map textMap, Map>> autoTableMap, List deleteFileStrList) { String returnMessage = "导出模板转移错误:"; InputStream in = null; FileOutputStream out = null; String zipFilePath = ""; String reportName = ""; try { String reportType = tReportTemplate.getReportType(); reportType = getTypeIfIsSAQ(tReportTemplate, reportType); reportType = getPositionIfJAQ(textMap, reportType); reportName = textMap.get("sendEmailFileName") + "_" + reportType + "_" + ReportTypeNameEnum.valueOf(tReportTemplate.getTemplateType()).getCode() + "_" + ReportTypeNameEnum.valueOf(tReportTemplate.getLangType()).getCode() + ".docx"; reportName = reportName.replaceAll(" ", "_"); out = getDownLoadFileOutputStream(reportName); log.info("reportTemplate:" + fileName); String templateType = tReportTemplate.getTemplateType(); setChageWord(fileName, out, textMap, tReportTemplate.getReportType(), templateType, autoTableMap); out.flush(); changColorIfJAQ(textMap, out, reportName, tReportTemplate.getReportType()); ShellTool.execLibreofficeCommand("pdf", EssConfig.getProfile() + "/" + reportName, EssConfig.getProfile() + "/"); zipFilePath = getPdfPath(reportName); deleteFileStrList.add(EssConfig.getProfile() + "/" + reportName); } catch (Exception ex) { returnMessage = returnMessage + ex.getMessage(); deleteFileStrList.add(EssConfig.getProfile() + "/" + reportName); log.error("导出模板转移错误:{}\n检查文件:" + fileName, returnMessage, ex); } finally { closeChannel(out); closeChannel(in); } return zipFilePath; } @Nullable private static String getPositionIfJAQ(Map textMap, String reportType) { if (Objects.equals(reportType, "JAQ")) { reportType = Optional.ofNullable(textMap.get("position")).map(p -> p.toString()).orElse("JAQ"); } return reportType; } private static void changColorIfJAQ(Map textMap, FileOutputStream out, String reportName, String reportType) throws IOException { if (Objects.equals(reportType, "JAQ")) { changTableColor(reportName, out, (List)textMap.get("JAQTableStyle")); } } private static String getTypeIfIsSAQ(TReportTemplate tReportTemplate, String reportType) { if (Objects.equals(tReportTemplate.getTemplateType(), TemplateTypeEnum.SAQ.getCode())) { reportType = TemplateTypeEnum.SAQ.getCode(); } return reportType; } private static String getPdfPath(String reportName) { return reportName.substring(0,reportName.lastIndexOf(".")) + ".pdf"; } public static void deleteFileByStr(List deleteFileStrList) { for (String deleteStr : deleteFileStrList) { File file = new File(deleteStr); file.delete(); } } private void zipWord(String fileName, List zipFileNameList) throws FileNotFoundException { List fileList = new ArrayList<>(); File fileZip = getAbsoluteFileZipByName(fileName + ".zip"); try { FileOutputStream zipOut = new FileOutputStream(fileZip); for (String zipFileName : zipFileNameList) { File file = new File(EssConfig.getProfile() + "/" + zipFileName); fileList.add(file); } ZipUtil.toZip(fileList, zipOut); } catch (Exception e) { e.printStackTrace(); } } private void zipKeepWord(String fileName, List zipFileNameList) throws FileNotFoundException { List fileList = new ArrayList<>(); File fileZip = getAbsoluteFileZipByName(fileName + ".zip"); FileOutputStream zipOut = new FileOutputStream(fileZip); for (String zipFileName : zipFileNameList) { File file = new File(EssConfig.getProfile() + "/" + zipFileName); fileList.add(file); } ZipUtil.toZip(fileList, zipOut); } private static FileOutputStream getDownLoadFileOutputStream(String fileName) throws FileNotFoundException { File outFile = new File(EssConfig.getProfile() + "/" + fileName); if (!outFile.getParentFile().exists()) { outFile.getParentFile().mkdirs(); } return new FileOutputStream(outFile); } private static void setChageWord(String fileName, OutputStream out, Map textMap, String reportType, String templateType, Map>> autoTableMap) throws IOException, org.apache.poi.openxml4j.exceptions.InvalidFormatException { String filePath = getTemplateDownLoadPathByUpLoad(fileName); XWPFDocument document = new XWPFDocument(POIXMLDocument.openPackage(getTemplateDownLoadPathByUpLoad(fileName))); changeText(document, textMap); addTableValue(document, autoTableMap); changeTable(document, textMap); changChar(textMap, document, reportType, templateType); document.write(out); } public static void changTableColor(String fileName, OutputStream out, List jaqTableStyleList) throws IOException { if (StringUtils.isEmpty(fileName) || CollUtil.isEmpty(jaqTableStyleList)) { return; } XWPFDocument document = new XWPFDocument(POIXMLDocument.openPackage(EssConfig.getProfile() + "/" + fileName)); if (Objects.isNull(document)) { return; } for (JAQTableStyle jaqTableStyle : jaqTableStyleList) { XWPFTable xwpfTable = document.getTables().get(jaqTableStyle.getTableNum()); for (Map.Entry jaqTableSet : jaqTableStyle.getRowColorMap().entrySet()) { XWPFTableRow row = xwpfTable.getRow(jaqTableSet.getKey()); List cells = row.getTableCells(); for (XWPFTableCell cell : cells) { List paragraphs = cell.getParagraphs(); for (XWPFParagraph paragraph : paragraphs) { List runs = paragraph.getRuns(); for (XWPFRun run : runs) { run.setColor(jaqTableSet.getValue()); } } } } } document.write(out); out.flush(); } private static void changChar(Map textMap, XWPFDocument document, String reportType, String templateType) { if (StringUtils.isEmpty(reportType) || StringUtils.isEmpty(templateType)) { return; } List charts = document.getCharts(); if (ExamUtil.isListEmpty(charts)) { return; } if (StringUtils.equals(reportType, "MAQ")) { setMAQCompleteChars(textMap, charts); } else if (StringUtils.equals(reportType, "RuiLin")){ setRuiLinChar(textMap, charts); } else { return; } } private static void setRuiLinChar(Map textMap, List charts) { try { int char0Size = charts.get(0).getCTChart().getPlotArea().getBarChartList().get(0).getSerList().get(0).getVal().getNumRef().getNumCache().getPtList().size(); System.out.println("睿邻第0个chart表个数:" + char0Size); int char1Size = charts.get(1).getCTChart().getPlotArea().getBarChartList().get(0).getSerList().get(0).getVal().getNumRef().getNumCache().getPtList().size(); System.out.println("睿邻第1个chart表个数:" + char1Size); Map setCharMap = new HashedMap(); setCharMap.put(12, WordUtil::set12RuilinChartList); setCharMap.put(38, WordUtil::set38RuilinChartList); setCharMap.put(4, WordUtil::set4RuilinChartList); XWPFChart xwpfChart0 = charts.get(0); List ptList = xwpfChart0.getCTChart().getPlotArea().getBarChartList().get(0).getSerList().get(0).getVal().getNumRef().getNumCache().getPtList(); setCharMap.get(char0Size).setsetRuilinChartList(textMap, ptList); XWPFChart xwpfChart1 = charts.get(1); ptList = xwpfChart1.getCTChart().getPlotArea().getBarChartList().get(0).getSerList().get(0).getVal().getNumRef().getNumCache().getPtList(); setCharMap.get(char1Size).setsetRuilinChartList(textMap, ptList); } catch (Exception e) { e.printStackTrace(); } } private static void set38RuilinChartList(Map textMap, List ptList) { ptList.get(37).setV(textMap.get(("P_Com1")).toString()); ptList.get(36).setV(textMap.get(("P_Com3")).toString()); ptList.get(35).setV(textMap.get(("P_Com4")).toString()); ptList.get(34).setV(textMap.get(("P_Com5")).toString()); ptList.get(33).setV(textMap.get(("P_Com7")).toString()); ptList.get(32).setV(textMap.get(("P_Com8")).toString()); ptList.get(31).setV(textMap.get(("P_Com9")).toString()); ptList.get(30).setV(textMap.get(("P_Com10")).toString()); ptList.get(29).setV(textMap.get(("P_Com11")).toString()); ptList.get(28).setV(textMap.get(("P_Com12")).toString()); ptList.get(27).setV(textMap.get(("P_Com13")).toString()); ptList.get(26).setV(textMap.get(("P_Com14")).toString()); ptList.get(25).setV(textMap.get(("P_Com15")).toString()); ptList.get(24).setV(textMap.get(("P_Com16")).toString()); ptList.get(23).setV(textMap.get(("P_Com17")).toString()); ptList.get(22).setV(textMap.get(("P_Com6")).toString()); ptList.get(21).setV(textMap.get(("P_Com19")).toString()); ptList.get(20).setV(textMap.get(("P_Com20")).toString()); ptList.get(19).setV(textMap.get(("P_Com21")).toString()); ptList.get(18).setV(textMap.get(("P_Com22")).toString()); ptList.get(17).setV(textMap.get(("P_Com23")).toString()); ptList.get(16).setV(textMap.get(("P_Com24")).toString()); ptList.get(15).setV(textMap.get(("P_Com25")).toString()); ptList.get(14).setV(textMap.get(("P_Com26")).toString()); ptList.get(13).setV(textMap.get(("P_Com27")).toString()); ptList.get(12).setV(textMap.get(("P_Com28")).toString()); ptList.get(11).setV(textMap.get(("P_Com29")).toString()); ptList.get(10).setV(textMap.get(("P_Com30")).toString()); ptList.get(9).setV(textMap.get(("P_Com31")).toString()); ptList.get(8).setV(textMap.get(("P_Com32")).toString()); ptList.get(7).setV(textMap.get(("P_Com33")).toString()); ptList.get(6).setV(textMap.get(("P_Com34")).toString()); ptList.get(5).setV(textMap.get(("P_Com35")).toString()); ptList.get(4).setV(textMap.get(("P_Com36")).toString()); ptList.get(3).setV(textMap.get(("P_Com37")).toString()); ptList.get(2).setV(textMap.get(("P_Com38")).toString()); ptList.get(1).setV(textMap.get(("P_Com39")).toString()); ptList.get(0).setV(textMap.get(("P_Com40")).toString()); } private static void set4RuilinChartList(Map textMap, List ptList) { ptList.get(0).setV(textMap.get(("P_Com301")).toString()); ptList.get(1).setV(textMap.get(("P_Com302")).toString()); ptList.get(2).setV(textMap.get(("P_Com303")).toString()); ptList.get(3).setV(textMap.get(("P_Com304")).toString()); } private static void set12RuilinChartList(Map textMap, List ptList) { ptList.get(0).setV(textMap.get("P_Com201").toString()); ptList.get(1).setV(textMap.get("P_Com202").toString()); ptList.get(2).setV(textMap.get("P_Com203").toString()); ptList.get(3).setV(textMap.get("P_Com204").toString()); ptList.get(4).setV(textMap.get("P_Com205").toString()); ptList.get(5).setV(textMap.get("P_Com206").toString()); ptList.get(6).setV(textMap.get("P_Com207").toString()); ptList.get(7).setV(textMap.get("P_Com208").toString()); ptList.get(8).setV(textMap.get("P_Com209").toString()); ptList.get(9).setV(textMap.get("P_Com210").toString()); ptList.get(10).setV(textMap.get("P_Com211").toString()); ptList.get(11).setV(textMap.get("P_Com212").toString()); } private static void setMAQCompleteChars(Map textMap, List charts) { String p_Task31 = textMap.get("P_Task31").toString(); String p_People32 = textMap.get("P_People32").toString(); XWPFChart xwpfChart = charts.get(0); if (!setMAQbarGraph(p_Task31, p_People32, xwpfChart)) { log.info("第二个是条形"); setMAQcanvasChart(p_Task31, p_People32, xwpfChart); } XWPFChart xwpfChartLeadershipFourSided = charts.get(1); if (!setMAQcanvasChart(p_Task31, p_People32, xwpfChartLeadershipFourSided)) { log.info("第一个是画布"); setMAQbarGraph(p_Task31, p_People32, xwpfChartLeadershipFourSided); } } private static boolean setMAQcanvasChart(String p_Task31, String p_People32, XWPFChart xwpfChartLeadershipFourSided) { try { CTChart ctChartFourSided = xwpfChartLeadershipFourSided.getCTChart(); CTPlotArea ctPlotAreaFourSided = ctChartFourSided.getPlotArea(); List scatterChartList = ctPlotAreaFourSided.getScatterChartList(); CTScatterChart ctScatterChart = scatterChartList.get(0); CTScatterSer ctScatterSer = ctScatterChart.getSerList().get(0); CTAxDataSource xVal = ctScatterSer.getXVal(); CTNumDataSource yVal = ctScatterSer.getYVal(); xVal.getNumRef().getNumCache().getPtList().get(0).setV(p_Task31); yVal.getNumRef().getNumCache().getPtList().get(0).setV(p_People32); } catch (Exception e) { e.printStackTrace(); return false; } return true; } private static boolean setMAQbarGraph(String p_Task31, String p_People32, XWPFChart xwpfChart) { try { CTChart ctChart = xwpfChart.getCTChart(); CTPlotArea ctPlotArea = ctChart.getPlotArea(); List barChartList = ctPlotArea.getBarChartList(); CTBarChart ctBarChart = barChartList.get(0); List serList = ctBarChart.getSerList(); CTBarSer ctBarSer = serList.get(0); CTNumDataSource val = ctBarSer.getVal(); val.getNumRef().getNumCache().getPtList().get(0).setV(p_Task31); val.getNumRef().getNumCache().getPtList().get(1).setV(p_People32); } catch (Exception e) { e.printStackTrace(); return false; } return true; } private String getTemplateDownLoadPath(String fileName) { return EssConfig.getReportTemplates() + fileName; } private static String getTemplateDownLoadPathByUpLoad(String fileName) { return EssConfig.getUploadPath() + fileName; } public static String getTemplatePicture(String pictureName) { return EssConfig.getReportTemplates() + pictureName; } private static void closeChannel(InputStream inputStream) { try { if (Objects.nonNull(inputStream)) { inputStream.close(); } } catch (IOException ioe) { log.error("关闭通道失败:{}", ioe.getMessage(), ioe); } } private static void closeChannel(OutputStream outputStream) { try { if (Objects.nonNull(outputStream)) { outputStream.close(); } } catch (IOException ioe) { log.error("关闭通道失败:{}", ioe.getMessage(), ioe); } } public File getAbsoluteFileZipByName(String filename) { String downloadPath = EssConfig.getDownloadPath() + filename; File desc = new File(downloadPath); if (!desc.getParentFile().exists()) { desc.getParentFile().mkdirs(); } return desc; } public static void insertNextPageChar(XWPFDocument document) { XWPFParagraph paragraph = document.createParagraph(); CTPPr ctpPr = paragraph.getCTP().addNewPPr(); ctpPr.addNewSectPr(); } private static String delDynList(String placeholder, List obj, XWPFParagraph oldParagraph, XWPFDocument templateDoc) { String placeholderValue = placeholder; List dataList = obj; Collections.reverse(dataList); XWPFRun oldRun = oldParagraph.getRuns().size() > 0 ? oldParagraph.getRuns().get(0) : null; Boolean isBold = Objects.nonNull(oldRun) ? oldRun.isBold() : false; for (int i = 0, size = dataList.size(); i < size; i++) { Object text = dataList.get(i); if (i == 0) { placeholderValue = String.valueOf(text); } else { XWPFParagraph paragraph = createParagraph(oldParagraph, templateDoc, oldRun, isBold, String.valueOf(text)); if (paragraph != null) { oldParagraph = paragraph; } } } return placeholderValue; } public static XWPFParagraph createParagraph(XWPFParagraph oldParagraph, XWPFDocument templateDoc, XWPFRun oldRun, boolean isBold, String... texts) { XmlCursor cursor = oldParagraph.getCTP().newCursor(); XWPFParagraph newPar = templateDoc.insertNewParagraph(cursor); newPar.getCTP().setPPr(oldParagraph.getCTP().getPPr()); copyParagraph(oldParagraph, newPar, oldRun, isBold, texts); return newPar; } ; private static void copyParagraph(XWPFParagraph sourcePar, XWPFParagraph targetPar, XWPFRun oldRun, boolean isBold, String... texts) { targetPar.setAlignment(sourcePar.getAlignment()); targetPar.setVerticalAlignment(sourcePar.getVerticalAlignment()); targetPar.setAlignment(sourcePar.getAlignment()); targetPar.setVerticalAlignment(sourcePar.getVerticalAlignment()); if (texts != null && texts.length > 0) { String[] arr = texts; for (int i = 0, len = texts.length; i < len; i++) { String text = arr[i]; XWPFRun run = targetPar.createRun(); run.setText(text); run.setFontFamily(oldRun.getFontFamily()); int fontSize = oldRun.getFontSize(); run.setFontSize((fontSize == -1) ? DEFAULT_FONT_SIZE : fontSize); run.setBold(isBold); run.setItalic(oldRun.isItalic()); run.setColor(oldRun.getColor()); } } String parText = targetPar.getText(); if (parText.indexOf("") != -1) { oldRun.setBold(isBold); setOtherStyle(parText, targetPar, 0, oldRun); } } public static void changeJAQStyle(Map textMap, int tableNum, int inum, String line) { JAQTableStyle jaqTableStyle = new JAQTableStyle(); jaqTableStyle.setTableNum(tableNum); Map rowColorMap = new HashMap<>(); jaqTableStyle.setRowColorMap(rowColorMap); for (Integer i = 1; i <= inum; i++) { if (Objects.equals(textMap.get(line + i.toString() + "C"), "1")) { rowColorMap.put(i, "C00000"); } } if (CollUtil.isNotEmpty(rowColorMap)) { List jaqTableStyleList = null; if (CollUtil.isNotEmpty((List) textMap.get("JAQTableStyle"))) { jaqTableStyleList = (List) textMap.get("JAQTableStyle"); } else { jaqTableStyleList = new ArrayList<>(); } jaqTableStyleList.add(jaqTableStyle); textMap.put("JAQTableStyle", jaqTableStyleList); } } }