java根据ftl模板导出word文档

    xiaoxiao2021-04-16  34

    步骤:

    1.新建word文档,指定好模板。占位符使用${name}

    2.另存为xml模式。

    3.用xml编辑器打开(例如EditPlus,firstobjext xml edit),对于被拆分的占位符,修改一下。如果有用到循环,自己需要添加循环。最后保存为ftl的文件---------mb.ftl。

    4.准备freemarker-2.3.13相关包

    5.直接上代码:

    /** * 临时生成word文档 * @author admin * */ public class WordUtil { @Autowired private static Logger logger = LogManager.getLogger(WordUtil.class); public static String path = "";//文件路径 private static final String FTL_FP = "/com/app/zf/itsm/web/configitem/ftl/"; //模板路径 private static Configuration configuration = null; static{ configuration = new Configuration(); configuration.setDefaultEncoding("utf-8");//设置默认的编码 //读配置文件 path = PropertiesUtil.get("FILE_PATH")+"/"; } /** * * @param dataMap 数据库数据 * @param ftl 替换的模板 * @return * @throws IOException */ public static String createDoc(Map dataMap,String ftl) throws IOException { // 设置模本装置方法和路径,FreeMarker支持多种模板装载方法。可以重servlet,classpath,数据库装载, // ftl文件存放路径 //configuration.setClassForTemplateLoading(,FTL_FP); //TemplateLoader templateLoader = new FileTemplateLoader(new File(FTL_FP)); //configuration.setDirectoryForTemplateLoading(new File(FTL_FP)); TemplateLoader templateLoader = new ClassTemplateLoader(WordUtil.class, FTL_FP); configuration.setTemplateLoader(templateLoader); Template t = null; try { // test.ftl为要装载的模板 t = configuration.getTemplate(ftl); t.setEncoding("utf-8"); } catch (IOException e) { e.printStackTrace(); } // 输出文档路径及名称 String file_name= dataMap.get("title") +".doc"; File outFile = new File(path+file_name); Writer out = null; try { out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8")); } catch (Exception e1) { logger.error(e1); file_name = ""; } try { t.process(dataMap, out); out.close(); } catch (TemplateException e2) { logger.error(e2); file_name = ""; } catch (IOException e) { logger.error(e); file_name = ""; } return file_name; } /**测试**/ public static void main(String str[]) { Map dataMap = new HashMap(); dataMap.put("title","wenyan名称"); dataMap.put("name","wenyan"); try { createDoc(dataMap,"mb.ftl"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } 这就完成了。

    转载请注明原文地址: https://ju.6miu.com/read-672459.html

    最新回复(0)