|
| 1 | +package org.topcat.docserver; |
| 2 | + |
| 3 | +import org.apache.poi.xwpf.extractor.XWPFWordExtractor; |
| 4 | +import org.apache.poi.xwpf.usermodel.*; |
| 5 | +import org.springframework.util.CollectionUtils; |
| 6 | + |
| 7 | +import java.io.*; |
| 8 | +import java.util.HashMap; |
| 9 | +import java.util.List; |
| 10 | +import java.util.Map; |
| 11 | +import java.util.Set; |
| 12 | + |
| 13 | +/** |
| 14 | + * Created by topcat on 2016/11/21. |
| 15 | + */ |
| 16 | +public class PoiWordTemplate implements WordTemplate { |
| 17 | + ; |
| 18 | + |
| 19 | + @Override |
| 20 | + public void fromTemplate(InputStream input, OutputStream output, Map<String, String> context) { |
| 21 | + if (CollectionUtils.isEmpty(context) || input == null || output == null) { |
| 22 | + return; |
| 23 | + } |
| 24 | + Set<String> keySet = context.keySet(); |
| 25 | + try { |
| 26 | + XWPFDocument doc = new XWPFDocument(input); |
| 27 | + for (XWPFParagraph p : doc.getParagraphs()) { |
| 28 | + List<XWPFRun> runs = p.getRuns(); |
| 29 | + if (runs != null) { |
| 30 | + for (XWPFRun r : runs) { |
| 31 | + String text = r.getText(0); |
| 32 | + for (String contextKey : |
| 33 | + keySet) { |
| 34 | + String key = String.format("$%s", contextKey); |
| 35 | + String value = context.get(contextKey); |
| 36 | + if (text != null && text.contains(key)) { |
| 37 | + text = text.replace(key, value); |
| 38 | + r.setText(text, 0); |
| 39 | + } |
| 40 | + } |
| 41 | + } |
| 42 | + } |
| 43 | + } |
| 44 | + for (XWPFTable tbl : doc.getTables()) { |
| 45 | + for (XWPFTableRow row : tbl.getRows()) { |
| 46 | + for (XWPFTableCell cell : row.getTableCells()) { |
| 47 | + for (XWPFParagraph p : cell.getParagraphs()) { |
| 48 | + for (XWPFRun r : p.getRuns()) { |
| 49 | + String text = r.getText(0); |
| 50 | + for (String contextKey : |
| 51 | + keySet) { |
| 52 | + String key = String.format("$%s", contextKey); |
| 53 | + String value = context.get(contextKey); |
| 54 | + if (text.contains(key)) { |
| 55 | + text = text.replace(key, value); |
| 56 | + r.setText(text); |
| 57 | + } |
| 58 | + } |
| 59 | + } |
| 60 | + } |
| 61 | + } |
| 62 | + } |
| 63 | + } |
| 64 | + doc.write(output); |
| 65 | + } catch (IOException e) { |
| 66 | + e.printStackTrace(); |
| 67 | + } |
| 68 | + |
| 69 | + } |
| 70 | + |
| 71 | + public static void main(String[] args) throws FileNotFoundException { |
| 72 | + Map<String, String> context = new HashMap<>(); |
| 73 | + context.put("name", "我"); |
| 74 | + new PoiWordTemplate().fromTemplate(new FileInputStream("/Users/topcat/Downloads/维护组关于各网站安全性加固方案(初稿).docx"), new FileOutputStream("/Users/topcat/Downloads/output.docx"), context); |
| 75 | + } |
| 76 | +} |
0 commit comments