將多個word檔案合併成一個檔案匯出
阿新 • • 發佈:2021-01-19
將多個word檔案合併成一個檔案匯出
public void bigPrintLabel(printLabelReq req, HttpServletRequest request, HttpServletResponse response) throws Exception { Optional<Sample> optionalSample = sampleRepository.findById(req.getId()); ValidationUtil.isNull(optionalSample, "Sample", "id", req.getId()); Sample sample = optionalSample.get(); LabOrder labOrder = sample.getLabOrder(); List<Map<String, String>> list = new ArrayList<>(); List<XWPFDocument> xwpfDocuments = new ArrayList<XWPFDocument>(); for (Integer i = 1; i <= req.getNumber(); i++) { Map<String, String> param = new HashMap<>(); if (i < 10) { param.put("${sampleNum}", labOrder.getOrderNumber() + "-0" + i); } else { param.put("${sampleNum}", labOrder.getOrderNumber() + "-" + i); } SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy.MM.dd"); //word中需要填入資料的地方使用${*}替換 param.put("${receiveTime}", simpleDateFormat.format(sample.getReceiveTime())); param.put("${completTime}", simpleDateFormat.format(labOrder.getDeadline())); param.put("${sampleName}", sample.getSampleName()); param.put("${sampleModle}", sample.getSampleModel()); param.put("${sampleRemark}", sample.getReceiveNum() + labOrder.getUnit()); param.put("${client}", labOrder.getContact().getClient().getCompany()); param.put("${makeUnit}", labOrder.getFactoryName()); param.put("${address}", labOrder.getContact().getClient().getAddress()); list.add(param); } for (Map<String, String> map : list) { //此處需要一個絕對路徑,因為上傳阿里雲伺服器,無法確定路徑值,使用以下方法獲取絕對路徑 String path = "tempLabel/"; String fileName = "fulisiyangpinbiaoqian.docx"; File outTempFile = new File(path + fileName); XWPFDocument xwpfDocument = generateWord(map, outTempFile.getAbsolutePath()); xwpfDocuments.add(xwpfDocument); } //這樣第一步將所有word內容替換之後生成多個 xwpfDocument //現在將多個xwpfDocument 進行合併 追加 生成word檔案 //先獲取一個模板 以第一個模板為基礎進行追加 XWPFDocument xwpfDocument = xwpfDocuments.get(0); for (int i = 0; i < xwpfDocuments.size(); i++) { //每次的追加為了避免樣式和格式混亂 加上分頁符 //當是只有一條資料的時候 直接輸出 if (i == 0) { xwpfDocument = xwpfDocuments.get(0); //xwpfDocuments.get(1).createParagraph().createRun().addBreak(BreakType.PAGE); continue; } else { //當存在多條時候 xwpfDocument = mergeWord(xwpfDocument, xwpfDocuments.get(i)); } } //合併之後返回XWPFDocument物件 寫出就可以了 String filePath = "tempFile/"; String fileName = "biaoqian.doc"; File outFile = new File(filePath + fileName); if (!outFile.getParentFile().exists()) { outFile.getParentFile().mkdirs(); } if (!outFile.exists()) { outFile.createNewFile(); } OutputStream outputStream = new FileOutputStream(outFile); xwpfDocument.write(outputStream); } public static XWPFDocument generateWord(Map<String, String> param, String filePath) { XWPFDocument doc = null; try { OPCPackage pack = POIXMLDocument.openPackage(filePath); doc = new XWPFDocument(pack); if (param != null && param.size() > 0) { //處理段落 String tempString = ""; Set<XWPFRun> runSet = new HashSet<>(); char lastChar = ' '; List<XWPFParagraph> paragraphList = doc.getParagraphs(); if (paragraphList != null && paragraphList.size() > 0) { for (XWPFParagraph paragraph : paragraphList) { List<XWPFRun> runs = paragraph.getRuns(); for (XWPFRun run : runs) { String text = run.getText(0); //檔案裡含有特殊字元,無法正常顯示 if ("1".equals(text)) { if ("1".equals(param.get("pending"))) { text = text.replace("1", "☑"); run.setText(text, 0);//往文本里新增一個打勾方框符號 } else { text = text.replace("1", "□"); run.setText(text, 0);//往文本里新增一個打勾方框符號 } } if ("2".equals(text)) { if ("1".equals(param.get("inspection"))) { text = text.replace("2", "☑"); run.setText(text, 0);//往文本里新增一個打勾方框符號 } else { text = text.replace("2", "□"); run.setText(text, 0);//往文本里新增一個打勾方框符號 } } if ("3".equals(text)) { if ("1".equals(param.get("checked"))) { text = text.replace("3", "☑"); run.setText(text, 0);//往文本里新增一個打勾方框符號 } else { text = text.replace("3", "□"); run.setText(text, 0);//往文本里新增一個打勾方框符號 } } if ("4".equals(text)) { if ("1".equals(param.get("abnormal"))) { text = text.replace("4", "☑"); run.setText(text, 0);//往文本里新增一個打勾方框符號 } else { text = text.replace("4", "□"); run.setText(text, 0);//往文本里新增一個打勾方框符號 } } if ("5".equals(text)) { if ("1".equals(param.get("reserve"))) { text = text.replace("5", "☑"); run.setText(text, 0);//往文本里新增一個打勾方框符號 } else { text = text.replace("5", "□"); run.setText(text, 0);//往文本里新增一個打勾方框符號 } } if (text == null) continue; text = replaceText(text, param); run.setText("", 0); run.setText(text, 0); for (int i = 0; i < text.length(); i++) { char ch = text.charAt(i); //System.out.println(ch); if (ch == '$') { runSet = new HashSet<>(); runSet.add(run); tempString = text; } else if (ch == '{') { if (lastChar == '$') { if (runSet.contains(run)) { } else { runSet.add(run); tempString = tempString + text; } } else { runSet = new HashSet<>(); tempString = ""; } } else if (ch == '}') { if (tempString != null && tempString.indexOf("${") >= 0) { if (runSet.contains(run)) { } else { runSet.add(run); tempString = tempString + text; } } else { runSet = new HashSet<>(); tempString = ""; } if (runSet.size() > 0) { System.out.println(tempString); String replaceText = replaceText(tempString, param); if (!replaceText.equals(tempString)) { int index = 0; XWPFRun aRun = null; for (XWPFRun tempRun : runSet) { tempRun.setText("", 0); if (index == 0) { aRun = tempRun; } index++; } aRun.setText(replaceText, 0); } runSet = new HashSet<>(); tempString = ""; } } else { if (runSet.size() <= 0) continue; if (runSet.contains(run)) continue; runSet.add(run); tempString = tempString + text; } lastChar = ch; } } } } } } catch (Exception e) { e.printStackTrace(); } return doc; } private static String replaceText(String text, Map<String, String> map) { if (text != null) { System.out.println(text); for (Map.Entry<String, String> entry : map.entrySet()) { String key = entry.getKey(); if (text.indexOf(key) != -1) { Object value = entry.getValue(); if (value instanceof String) {//文字替換 text = text.replace(key, value.toString()); } } } } return text; } //兩個物件進行追加 public static XWPFDocument mergeWord(XWPFDocument document, XWPFDocument doucDocument2) throws Exception { XWPFDocument src1Document = document; //XWPFParagraph p = src1Document.createParagraph(); //設定分頁符 //p.setPageBreak(true); CTBody src1Body = src1Document.getDocument().getBody(); XWPFDocument src2Document = doucDocument2; CTBody src2Body = src2Document.getDocument().getBody(); //下面這句會在尾部多一個換行符 //XWPFParagraph p2 = src2Document.createParagraph(); XmlOptions optionsOuter = new XmlOptions(); optionsOuter.setSaveOuter(); String appendString = src2Body.xmlText(); String srcString = src1Body.xmlText(); String prefix = srcString.substring(0, srcString.indexOf(">") + 1); String mainPart = srcString.substring(srcString.indexOf(">") + 1, srcString.lastIndexOf("<")); String sufix = srcString.substring(srcString.lastIndexOf("<")); String addPart = appendString.substring(appendString.indexOf(">") + 1, appendString.lastIndexOf("<")); CTBody makeBody = CTBody.Factory.parse(prefix + mainPart + addPart + sufix); src1Body.set(makeBody); return src1Document; }