第一篇导出pdf 中导出docx比较复杂 链接 , http://blog.csdn.net/rd_moon/article/details/78995563
关于xml的生成请查看第一篇,点击上方链接
这篇生成docx比较精简 ,
import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateException; import java.io.*; import java.util.*; import java.util.zip.ZipEntry; import java.util.zip.ZipException; import java.util.zip.ZipFile; import java.util.zip.ZipOutputStream; /** * 其实docx属于zip的一种,这里只需要操作word/document.xml中的数据,其他的数据不用动 * * */ public class XmlToDocx { /** * @Description 根据参数生成docx合同文档 * @author belle.wang * @param templatepath 模板所在文件夹 * @param docxname docx格式模板文件名(不带路径) * @param xmlname xml格式模板,有freemaker标记(不带路径) * @param tmpxmlpath 临时xml文件路径 * @param targetPath 目标路径 * @param param 待填充数据 * @return * @throws Exception */ public static boolean toDocx(String templatepath, String docxname, String xmlname, String tmpxmlpath, String targetPath, Map<String, Object> param) { try { Configuration cfg = new Configuration(); cfg.setDirectoryForTemplateLoading(new File(templatepath)); Template template = cfg.getTemplate(xmlname); template.setOutputEncoding("UTF-8"); Writer out = new FileWriter(new File(tmpxmlpath)); // 数据放到模板xml里面,生成带数据的xml template.process(param, out); if (out != null) { out.close(); } // 带数据的xml生成docx File file = new File(tmpxmlpath); File docxFile = new File(templatepath + "/" + docxname); ZipFile zipFile = new ZipFile(docxFile); Enumeration<? extends ZipEntry> zipEntrys = zipFile.entries(); ZipOutputStream zipout = new ZipOutputStream(new FileOutputStream(targetPath)); int len = -1; byte[] buffer = new byte[1024]; while (zipEntrys.hasMoreElements()) { ZipEntry next = zipEntrys.nextElement(); InputStream is = zipFile.getInputStream(next); // 把输入流的文件传到输出流中 如果是word/document.xml由我们输入 zipout.putNextEntry(new ZipEntry(next.toString())); if ("word/document.xml".equals(next.toString())) { InputStream in = new FileInputStream(file); while ((len = in.read(buffer)) != -1) { zipout.write(buffer, 0, len); } in.close(); } else { while ((len = is.read(buffer)) != -1) { zipout.write(buffer, 0, len); } is.close(); } } zipout.close(); } catch (Exception e) { e.printStackTrace(); } return true; } public static void main(String[] args) throws IOException, TemplateException { // 路径 String templatepath = "D:/"; String docxname = "qqjr_template.docx"; String xmlname = "qqjr.xml"; String tmpxmlpath = "D:\\complete.xml"; String targetpath = "D:\\complete.docx"; // 数据 Map<String,Object> data = new HashMap(); data.put("sqdw","这里是文字"); // 生成文档 try { toDocx(templatepath, docxname, xmlname, tmpxmlpath, targetpath, data); } catch (Exception e) { e.printStackTrace(); } } }关于docx中生成图片的参考下面链接
参考链接:http://blog.csdn.net/u010588262/article/details/73105882