Java读取word模板,并动态生成word

时间:2025-03-23 12:41:48
public class WordTest { public static void main(String[] args) { try { // 模板文件地址 String filePath = "D:\\test\\"; // 读取模板后保存生成word的地址 String outPath = "D:\\test\\"; // 为成绩2的显示绑定行循环,成绩1与3可以不要此行 LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy(); // 将score22设置为行循环绑定的数据源的key,即key是score22的value会在模板中的{{score22}}处进行解析,成绩1与3可以不要此行 Configure configure = Configure.builder().bind("score22", policy).build(); // 读取模板、数据并渲染 XWPFTemplate template = XWPFTemplate.compile(new File(filePath), configure).render( // 创建一个map并设置为只读map Collections.unmodifiableMap(new HashMap<String, Object>() { { // 设置普通文本的值 put("username", "张三"); // 设置选择框 String sex = "????"; List<String> list = Arrays.asList("????", "????"); for (int index = 0; index < list.size(); index++) { if (list.get(index).equals(sex)) { put("checkBox" + index, "☑"); } else { put("checkBox" + index, "□"); } } // 设置照片的值 FileInputStream inputStream = new FileInputStream(new File("D:\\test\\1 ")); PictureRenderData pictureRenderData = new PictureRenderData(100, 150, PictureType.suggestFileType(".png"), inputStream); put("picture", pictureRenderData); inputStream.close(); // 其他业务获取到数据源 String score = "[{\"name\":\"Chinese\",\"score\":99},{\"name\":\"Math\",\"score\":98},{\"name\":\"English\",\"score\":97}]"; // 成绩1在表格里循环 List<Score> forms = JSON.parseArray(score, Score.class); for (int i = 0; i < forms.size(); i++) { put("name" + i, forms.get(i).getName()); put("score" + i, forms.get(i).getScore()); } // 成绩2 put("score22", forms); put("total", 110); // 成绩3 put("score", forms); } }) ); // 文件是否已存在,则删除 File file = new File(outPath); if (file.exists()){ file.delete(); } // 生成word保存在指定目录 template.writeToFile(outPath); template.close(); } catch (Exception e) { e.printStackTrace(); } } }