依赖: freemarker
org.freemarkerfreemarker2.3.31
代码展示
import freemarker.template.Configuration;import freemarker.template.Template;import freemarker.template.TemplateException;import java.io.FileWriter;import java.io.IOException;import java.io.StringWriter;import java.util.HashMap;import java.util.Map;/** * @Description: * @Author zhou * @Date 2023/9/26 - 13:19 */public class TestXMLtoWord {public static void main(String[] args) {Map dataModel = getMapData();try {// 创建FreeMarker配置Configuration cfg = new Configuration(Configuration.VERSION_2_3_31);// 设置模板文件的位置cfg.setClassForTemplateLoading(TestXMLtoWord.class, "/templates");// 获取模板Template template = cfg.getTemplate("name.xml");// 使用FreeMarker渲染模板并将内容添加到Word文档StringWriter writer = new StringWriter();// 替换关键字template.process(dataModel, writer);// .doc .docx .xml 等文件都可以,只需要修改后缀try (FileWriter fileWriter = new FileWriter("output.doc")) {fileWriter.write(writer.toString());} catch (IOException e) {e.printStackTrace();}System.out.println("Word文档已生成成功!");} catch (IOException | TemplateException e) {e.printStackTrace();}}// 创建数据模型public static Map getMapData() {Map dataModel = new HashMap();dataModel.put("CREATE_MAN", "zhou");dataModel.put("CHECK_MAN", "zhou");dataModel.put("d1_operate_time_1", "test1");dataModel.put("d1_operate_time_2", "test2");dataModel.put("d1_operate_time_3", "test3");dataModel.put("d1_file_num_last_1", "tes1232t");dataModel.put("d1_file_num_last_2", "tes321t");dataModel.put("d1_file_num_last_3", "t111est");dataModel.put("d1_file_size_last_1", "tes222t");dataModel.put("d1_file_size_last_2", "te44st");dataModel.put("d1_file_size_last_3", "te33st");dataModel.put("d1_file_num_1", "te11st");dataModel.put("d1_file_num_2", "tes22t");dataModel.put("d1_file_num_3", "te33st");dataModel.put("d1_file_size_1", "te666st");dataModel.put("d1_file_size_2", "t222st");dataModel.put("d1_file_size_3", "te111st");return dataModel;}}
文件展示
name.xml:word另存为xml文件
位置:\src\main\resources\templates
output.doc:.doc .docx .xml 等文件都可以,只需要修改后缀