首页 > 代码库 > 使用word的xml模板生成.doc文件
使用word的xml模板生成.doc文件
一、编辑模板 替换地方以变量标记如“案件编号”可写成{caseNo}
template.xml
二、准备数据 以HashMap封装数据,原理是替换模板中的变量
三、替换操作
选择输出位置:writePath
WordUtil.printWordbyXMLWithOutputPath(templateFile, writePath, filename, dataMap);
/** * 打印word文档(传入参数需要传入输出文件的保存路径的) * @param templateFile * @param writeFilePath * @param writeFileName * @param analysisData 要替换的数据,map的形式传递 * @throws Exception */ public static void printWordbyXMLWithOutputPath(String templateFile, String writeFilePath, String writeFileName, Map<String, String> analysisData) throws Exception{ writeFilePath = makePathFile(writeFilePath); String writeFile = ""; if(writeFilePath.endsWith("\\") || writeFilePath.endsWith("/")){ writeFile += writeFilePath + writeFileName; }else{ writeFile = writeFilePath + FILE_SEPARATOR + writeFileName; } printWordByXML(templateFile, writeFile, analysisData); }
/** * 打印word文档(输出路径不需要单独指出,保存在writeFile中即可) * @param templateFile * @param writeFile * @param analysisData * @throws Exception */ public static void printWordByXML(String templateFile, String writeFile, Map<String, String> analysisData) throws Exception{ FileInputStream fis = null; InputStreamReader isr = null; BufferedReader in = null; FileOutputStream fos = null; OutputStreamWriter osw = null; BufferedWriter out = null; try { fis = new FileInputStream(templateFile); isr = new InputStreamReader(fis, "UTF-8"); in = new BufferedReader(isr); fos = new FileOutputStream(writeFile); osw = new OutputStreamWriter(fos, "UTF-8"); out = new BufferedWriter(osw); String s; while ((s = in.readLine()) != null) { for (String key : analysisData.keySet()) { String value = analysisData.get(key); if (value != null) { s = s.replace(key, value); } else { s = s.replace(key, ""); } } out.write(s); out.newLine(); } } catch (Exception e) { e.printStackTrace(); } finally{ if(out != null){ out.close(); } if(osw != null){ osw.close(); } if(fos != null){ fos.close(); } if(in != null){ in.close(); } if(isr != null){ isr.close(); } if(fis != null){ fis.close(); } // DeleteFile(templateFile); } }
/** * 验证目录是否存在,如果不存在,则创建对应目录。 * @param filePathName */ public static String makePathFile(String filePathName){ File pathFile = new File(filePathName); if(!pathFile.exists()){ pathFile.mkdirs(); } File childFile = new File(pathFile + "\\\\" + DateTools.dateToString( new Date(),"yyyyMM"));//xiexiangning if (!childFile.exists()) { childFile.mkdir(); } return childFile + "\\\\"; }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。