Java POI Word模板数据填充

Posted Less is More(少即是多)

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java POI Word模板数据填充相关的知识,希望对你有一定的参考价值。

  1 package ***;
  2 
  3 import java.io.FileInputStream;
  4 import java.io.FileNotFoundException;
  5 import java.io.FileOutputStream;
  6 import java.util.ArrayList;
  7 import java.util.HashMap;
  8 import java.util.List;
  9 import java.util.Map;
 10 import java.util.Set;
 11 
 12 import org.apache.poi.util.Units;
 13 import org.apache.poi.xwpf.usermodel.XWPFDocument;
 14 import org.apache.poi.xwpf.usermodel.XWPFParagraph;
 15 import org.apache.poi.xwpf.usermodel.XWPFRun;
 16 import org.apache.poi.xwpf.usermodel.XWPFTable;
 17 import org.apache.poi.xwpf.usermodel.XWPFTableCell;
 18 import org.apache.poi.xwpf.usermodel.XWPFTableRow;
 19 
 20 /**
 21  * 文件数据替换
 22  * @author 23  *
 24  */
 25 
 26 public class ReplaceWord {
 27 
 28     public static String path = "模板文件的路径/test.docx";
 29 
 30     public static void main(String[] args) throws Exception {
 31         Map<String, Object> data = new HashMap<>();
 32         Map<String, Object> pic = new HashMap<>();
 33 
 34         pic.put("${carpicture}", "Files/sign.png");
 35         pic.put("${licensecopy}", "Files/sign.png");
 36         data.put("${seal}", "1");
 37         pic.put("${sing01}", "Files/sign.png");
 38         pic.put("${sing02}", "Files/sign.png");
 39         System.out.println(pic.containsKey("${carpicture}"));
 40 
 41         // 列表(List)是对象的有序集合
 42         List<List<String[]>> tabledataList = new ArrayList<>();
 43         getWord(data, tabledataList, pic);
 44     }
 45 
 46     public static void getWord(Map<String, Object> data, List<List<String[]>> tabledataList, Map<String, Object> picmap)
 47             throws Exception {
 48         try (FileInputStream is = new FileInputStream(path); XWPFDocument document = new XWPFDocument(is)) {
 49             // 替换掉表格之外的文本(仅限文本)
 50             changeText(document, data);
 51 
 52             // 替换表格内的文本对象
 53             changeTableText(document, data);
 54 
 55             // 替换图片
 56             changePic(document, picmap);
 57 
 58             // 替换表格内的图片对象
 59             changeTablePic(document, picmap);
 60 
 61             long time = System.currentTimeMillis();// 获取系统时间
 62             System.out.println(time); // 打印时间
 63             // 使用try和catch关键字捕获异常
 64             try (FileOutputStream out = new FileOutputStream("生成的文件路径/文件名" + ".docx")) {
 65                 document.write(out);
 66             }
 67         } catch (FileNotFoundException e) {
 68             e.printStackTrace();
 69         }
 70     }
 71 
 72     /**
 73      * 替换段落文本
 74      * @param document docx解析对象
 75      * @param textMap 需要替换的信息集合
 76      *
 77      */
 78     public static void changeText(XWPFDocument document, Map<String, Object> textMap) {
 79         // 获取段落集合
 80         // 返回包含页眉或页脚文本的段落
 81         List<XWPFParagraph> paragraphs = document.getParagraphs();
 82         // 增强型for循环语句,前面一个为声明语句,后一个为表达式
 83         for (XWPFParagraph paragraph : paragraphs) {
 84             // 判断此段落是否需要替换
 85             String text = paragraph.getText();// 检索文档中的所有文本
 86             if (checkText(text)) {
 87                 List<XWPFRun> runs = paragraph.getRuns();
 88                 for (XWPFRun run : runs) {
 89                     // 替换模板原来位置
 90                     Object ob = changeValue(run.toString(), textMap);
 91                     if (ob instanceof String) {
 92                         if (textMap.containsKey(run.toString())) {
 93                             run.setText((String) ob, 0);
 94                         }
 95                     }
 96                 }
 97             }
 98         }
 99     }
100 
101     /* 检查文本中是否包含指定的字符(此处为“$”),并返回值 */
102     public static boolean checkText(String text) {
103         boolean check = false;
104         if (text.contains("$")) {
105             check = true;
106         }
107         return check;
108     }
109 
110     /**
111      * 替换图片
112      * @param document
113      * @param textMap
114      * @throws Exception
115      */
116 
117     public static void changePic(XWPFDocument document, Map<String, Object> textMap) throws Exception {
118         // 获取段落集合
119         List<XWPFParagraph> paragraphs = document.getParagraphs();
120 
121         for (XWPFParagraph paragraph : paragraphs) {
122             // 判断此段落是否需要替换
123             String text = paragraph.getText();
124             if (checkText(text)) {
125                 List<XWPFRun> runs = paragraph.getRuns();
126                 for (XWPFRun run : runs) {
127                     // 替换模板原来位置
128                     Object ob = changeValue(run.toString(), textMap);
129                     if (ob instanceof String) {
130                         if (textMap.containsKey(run.toString())) {
131                             run.setText("", 0);
132                             try (FileInputStream is = new FileInputStream((String) ob)) {
133                                 run.addPicture(is, XWPFDocument.PICTURE_TYPE_PNG, (String) ob, Units.toEMU(100),
134                                         Units.toEMU(100));
135                             }
136                         }
137                     }
138                 }
139             }
140         }
141     }
142 
143     public static void changeTableText(XWPFDocument document, Map<String, Object> data) {
144         // 获取文件的表格
145         List<XWPFTable> tableList = document.getTables();
146 
147         // 循环所有需要进行替换的文本,进行替换
148         for (int i = 0; i < tableList.size(); i++) {
149             XWPFTable table = tableList.get(i);
150             if (checkText(table.getText())) {
151                 List<XWPFTableRow> rows = table.getRows();
152                 // 遍历表格,并替换模板
153                 eachTable(document, rows, data);
154             }
155         }
156     }
157 
158     public static void changeTablePic(XWPFDocument document, Map<String, Object> pic) throws Exception {
159         List<XWPFTable> tableList = document.getTables();
160 
161         // 循环所有需要替换的文本,进行替换
162         for (int i = 0; i < tableList.size(); i++) {
163             XWPFTable table = tableList.get(i);
164             if (checkText(table.getText())) {
165                 List<XWPFTableRow> rows = table.getRows();
166                 System.out.println("简单表格替换:" + rows);
167                 // 遍历表格,并替换模板
168                 eachTablePic(document, rows, pic);
169             }
170         }
171     }
172 
173     public static void eachTablePic(XWPFDocument document, List<XWPFTableRow> rows, Map<String, Object> pic)
174             throws Exception {
175         for (XWPFTableRow row : rows) {
176             List<XWPFTableCell> cells = row.getTableCells();
177             for (XWPFTableCell cell : cells) {
178                 // 判断单元格是否需要替换
179                 if (checkText(cell.getText())) {
180                     List<XWPFParagraph> paragraphs = cell.getParagraphs();
181                     for (XWPFParagraph paragraph : paragraphs) {
182                         List<XWPFRun> runs = paragraph.getRuns();
183                         for (XWPFRun run : runs) {
184                             Object ob = changeValue(run.toString(), pic);
185                             if (ob instanceof String) {
186                                 System.out.println("run" + "‘" + run.toString() + "‘");
187                                 if (pic.containsKey(run.toString())) {
188                                     System.out.println("run" + run.toString() + "替换为" + ob);
189                                     run.setText("", 0);
190                                     try (FileInputStream is = new FileInputStream((String) ob)) {
191                                         run.addPicture(is, XWPFDocument.PICTURE_TYPE_PNG, (String) ob, Units.toEMU(100),
192                                                 Units.toEMU(100));
193                                     }
194                                 } else {
195                                     System.out.println("‘" + run.toString() + "‘ 不匹配");
196                                 }
197                             }
198                         }
199                     }
200                 }
201             }
202         }
203     }
204 
205     public static Object changeValue(String value, Map<String, Object> textMap) {
206         Set<Map.Entry<String, Object>> textSets = textMap.entrySet();
207         Object valu = "";
208         for (Map.Entry<String, Object> textSet : textSets) {
209             // 匹配模板与替换值 格式${key}
210             String key = textSet.getKey();
211             if (value.contains(key)) {
212                 valu = textSet.getValue();
213             }
214         }
215         return valu;
216     }
217 
218     public static void eachTable(XWPFDocument document, List<XWPFTableRow> rows, Map<String, Object> textMap) {
219         for (XWPFTableRow row : rows) {
220             List<XWPFTableCell> cells = row.getTableCells();
221             for (XWPFTableCell cell : cells) {
222                 // 判断单元格是否需要替换
223                 if (checkText(cell.getText())) {
224                     // System.out.println("cell:" + cell.getText());
225                     List<XWPFParagraph> paragraphs = cell.getParagraphs();
226                     for (XWPFParagraph paragraph : paragraphs) {
227                         List<XWPFRun> runs = paragraph.getRuns();
228                         for (XWPFRun run : runs) {
229 
230                             Object ob = changeValue(run.toString(), textMap);
231                             if (ob instanceof String) {
232 
233                                 System.out.println("run:" + "‘" + run.toString() + "‘");
234                                 if (textMap.containsKey(run.toString())) {
235                                     System.out.println("run:" + run.toString() + "替换为" + ob);
236                                     run.setText((String) ob, 0);
237                                 } else {
238                                     System.out.println("‘" + run.toString() + "‘不匹配");
239                                 }
240                             }
241                         }
242                     }
243                 }
244             }
245         }
246     }
247 }

 

以上是关于Java POI Word模板数据填充的主要内容,如果未能解决你的问题,请参考以下文章

poi-tl——Word模板生成器

java程序,使用poi,用word模板,如何在分页后重复展示表头

java poi 生成word表格怎么 让表格填充整个页面和合并单元格

Java操作Poi--word图表中颜色的设置

Java操作Poi--word图表中颜色的设置

使用java Apache poi 根据word模板生成word报表