简单]使用docx4j制作简单的word(2007)小结"/>
[简单]使用docx4j制作简单的word(2007)小结
如果在使用docx4j的过程中有一些效果自己不会写,上网也没搜索到答案,怎么解决呢?
可以把word 2007解压,word 2007解压后是很多xml,docx4j的sample例子上面有解压word的代码,如下:
Java代码 - import java.io.File;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import org.apachemons.io.IOUtils;
- import org.docx4j.openpackaging.exceptions.Docx4JException;
- import org.docx4j.openpackaging.io3.Load3;
- import org.docx4j.openpackaging.io3.Save;
- import org.docx4j.openpackaging.io3.stores.UnzippedPartStore;
- import org.docx4j.openpackaging.io3.stores.ZipPartStore;
- import org.docx4j.openpackaging.packages.OpcPackage;
- import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
- public class Word_解压_Unzip_S3_Test {
- public static void main(String[] args) throws Exception {
- Word_解压_Unzip_S3_Test t = new Word_解压_Unzip_S3_Test();
- //t.unzipWord("f:/saveFile/temp/test_t.docx","f:/saveFile/temp/Unzip_3");
- t.unzipWord("f:/saveFile/temp/img_word.docx","f:/saveFile/temp/Unzip_8");
- //t.zipXml("f:/saveFile/temp/Unzip_2", "f:/saveFile/temp/test_t2.docx");
- }
- public void unzipWord(String fileName,String outFilePath) throws Exception {
- WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage
- .load(new java.io.File(fileName));
- File baseDir = new File(outFilePath);
- baseDir.mkdir();
- UnzippedPartStore ups = new UnzippedPartStore(baseDir);
- ups.setSourcePartStore(wordMLPackage.getSourcePartStore());
- Save saver = new Save(wordMLPackage, ups);
- saver.save(null);
- }
- public void zipXml(String inputfilepath, String outFilePath)
- throws Exception {
- System.out.println(inputfilepath);
- // Load the docx
- File baseDir = new File(inputfilepath);
- UnzippedPartStore partLoader = new UnzippedPartStore(baseDir);
- final Load3 loader = new Load3(partLoader);
- OpcPackage opc = loader.get();
- // Save it zipped
- ZipPartStore zps = new ZipPartStore();
- zps.setSourcePartStore(opc.getSourcePartStore());
- Save saver = new Save(opc, zps);
- FileOutputStream fos = null;
- try {
- fos = new FileOutputStream(new File(outFilePath));
- saver.save(fos);
- } catch (FileNotFoundException e) {
- throw new Docx4JException("Couldn't save " + outFilePath, e);
- } finally {
- IOUtils.closeQuietly(fos);
- }
- }
- }
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;import org.apachemons.io.IOUtils;
import org.docx4j.openpackaging.exceptions.Docx4JException;
import org.docx4j.openpackaging.io3.Load3;
import org.docx4j.openpackaging.io3.Save;
import org.docx4j.openpackaging.io3.stores.UnzippedPartStore;
import org.docx4j.openpackaging.io3.stores.ZipPartStore;
import org.docx4j.openpackaging.packages.OpcPackage;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;public class Word_解压_Unzip_S3_Test {public static void main(String[] args) throws Exception {Word_解压_Unzip_S3_Test t = new Word_解压_Unzip_S3_Test();//t.unzipWord("f:/saveFile/temp/test_t.docx","f:/saveFile/temp/Unzip_3");t.unzipWord("f:/saveFile/temp/img_word.docx","f:/saveFile/temp/Unzip_8");//t.zipXml("f:/saveFile/temp/Unzip_2", "f:/saveFile/temp/test_t2.docx");}public void unzipWord(String fileName,String outFilePath) throws Exception {WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(new java.io.File(fileName));File baseDir = new File(outFilePath);baseDir.mkdir();UnzippedPartStore ups = new UnzippedPartStore(baseDir);ups.setSourcePartStore(wordMLPackage.getSourcePartStore());Save saver = new Save(wordMLPackage, ups);saver.save(null);}public void zipXml(String inputfilepath, String outFilePath)throws Exception {System.out.println(inputfilepath);// Load the docxFile baseDir = new File(inputfilepath);UnzippedPartStore partLoader = new UnzippedPartStore(baseDir);final Load3 loader = new Load3(partLoader);OpcPackage opc = loader.get();// Save it zippedZipPartStore zps = new ZipPartStore();zps.setSourcePartStore(opc.getSourcePartStore());Save saver = new Save(opc, zps);FileOutputStream fos = null;try {fos = new FileOutputStream(new File(outFilePath));saver.save(fos);} catch (FileNotFoundException e) {throw new Docx4JException("Couldn't save " + outFilePath, e);} finally {IOUtils.closeQuietly(fos);}}
}
里面的内容为:
和excel 2007解压的内容差不多。
word内容在document.xml,页眉页脚在header.xml和footer.xml中,想要什么效果粗暴点就是把xml内容替换掉,后面会讲到这方面的内容,也可以这样做,先把原word解压一份,在word上面添加自己想要的效果,在解压,对比2份文件对应的xml内容就知道要修改那些类了,如下:
想要好看点就先格式化xml,如下:
图中就是设置页眉底部的边框xml代码部分,位置在p-->ppr->pbdr下面,名字叫between,相应的代码可以这么写:
Java代码
- P p = factory.createP();
- PPr pPr = p.getPPr();
- if (pPr == null) {
- pPr = factory.createPPr();
- }
- PBdr pBdr=pPr.getPBdr();
- if(pBdr==null){
- pBdr=factory.createPPrBasePBdr();
- }
- CTBorder value=new CTBorder();
- value.setVal(STBorder.SINGLE);
- value.setColor("000000");
- value.setSpace(new BigInteger("0"));
- value.setSz(new BigInteger("3"));
- pBdr.setBetween(value);
- pPr.setPBdr(pBdr);
P p = factory.createP();
PPr pPr = p.getPPr();
if (pPr == null) {pPr = factory.createPPr();
}
PBdr pBdr=pPr.getPBdr();
if(pBdr==null){pBdr=factory.createPPrBasePBdr();
}
CTBorder value=new CTBorder();
value.setVal(STBorder.SINGLE);
value.setColor("000000");
value.setSpace(new BigInteger("0"));
value.setSz(new BigInteger("3"));
pBdr.setBetween(value);
pPr.setPBdr(pBdr);
setBetween的时候就知道里面是什么类型的变量了,其他的差不多也可以这么做。
在使用docx4j的过程中,有种感觉就是docx4j其实是在拼xml,再压缩为word,有种自己替换变量制作word的冲动,这个想法已经有人写过了,他的做法如下,
1)制作一份模版word,变量名用${}括起来
2)解压word为xml,替换xml内容,再压缩为word
代码如下:
- /*
- * To change this template, choose Tools | Templates
- * and open the template in the editor.
- */
- package com.test;
- import java.io.File;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.util.Enumeration;
- import java.util.zip.ZipEntry;
- import java.util.zip.ZipException;
- import java.util.zip.ZipFile;
- import org.apachemons.io.FileUtils;
- /**
- *
- * @author eg
- */
- public class ZipHelper {
- private static final int BUFFER = 1024;
- public void zipFolder(String folderToZip, String destZip,
- boolean includeInitialFolder) throws Exception {
- zipFolder(new File(folderToZip), new File(destZip),
- includeInitialFolder);
- }
- public void zipFolder(String folderToZip, String destZip) throws Exception {
- zipFolder(new File(folderToZip), new File(destZip));
- }
- public static void zipFolder(File folderToZip, File destZip)
- throws Exception {
- zipFolder(folderToZip, destZip, true);
- }
- public static void zipFolder(File folderToZip, File destZip,
- boolean includeInitialFolder) throws Exception {
- ZipFolderHelper helper = new ZipFolderHelper();
- helper.setIncludeInitialFolder(includeInitialFolder);
- helper.process(folderToZip, destZip);
- }
- public static void unzip(String inFile, String outFolder)
- throws IOException {
- unzip(new File(inFile), new File(outFolder));
- }
- /**
- * @param zipFile
- * @param dest
- */
- public static void unzip(File in, File dest) throws ZipException,
- IOException {
- FileUtils.deleteDirectory(dest);
- ZipFile zipFile = new ZipFile(in);
- Enumeration<?> files = zipFile.entries();
- File f = null;
- FileOutputStream fos = null;
- while (files.hasMoreElements()) {
- try {
- ZipEntry entry = (ZipEntry) files.nextElement();
- InputStream eis = zipFile.getInputStream(entry);
- byte[] buffer = new byte[BUFFER];
- int bytesRead = 0;
- f = new File(dest.getAbsolutePath() + File.separator
- + entry.getName());
- if (entry.isDirectory()) {
- f.mkdirs();
- continue;
- } else {
- f.getParentFile().mkdirs();
- f.createNewFile();
- }
- fos = new FileOutputStream(f);
- while ((bytesRead = eis.read(buffer)) != -1) {
- fos.write(buffer, 0, bytesRead);
- }
- } finally {
- if (fos != null) {
- try {
- fos.close();
- } catch (IOException e) {
- // ignore
- }
- }
- }
- }
- }
- }
/** To change this template, choose Tools | Templates* and open the template in the editor.*/
package com.test;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
import org.apachemons.io.FileUtils;
/*** * @author eg*/
public class ZipHelper {private static final int BUFFER = 1024;public void zipFolder(String folderToZip, String destZip,boolean includeInitialFolder) throws Exception {zipFolder(new File(folderToZip), new File(destZip),includeInitialFolder);}public void zipFolder(String folderToZip, String destZip) throws Exception {zipFolder(new File(folderToZip), new File(destZip));}public static void zipFolder(File folderToZip, File destZip)throws Exception {zipFolder(folderToZip, destZip, true);}public static void zipFolder(File folderToZip, File destZip,boolean includeInitialFolder) throws Exception {ZipFolderHelper helper = new ZipFolderHelper();helper.setIncludeInitialFolder(includeInitialFolder);helper.process(folderToZip, destZip);}public static void unzip(String inFile, String outFolder)throws IOException {unzip(new File(inFile), new File(outFolder));}/*** @param zipFile* @param dest*/public static void unzip(File in, File dest) throws ZipException,IOException {FileUtils.deleteDirectory(dest);ZipFile zipFile = new ZipFile(in);Enumeration<?> files = zipFile.entries();File f = null;FileOutputStream fos = null;while (files.hasMoreElements()) {try {ZipEntry entry = (ZipEntry) files.nextElement();InputStream eis = zipFile.getInputStream(entry);byte[] buffer = new byte[BUFFER];int bytesRead = 0;f = new File(dest.getAbsolutePath() + File.separator+ entry.getName());if (entry.isDirectory()) {f.mkdirs();continue;} else {f.getParentFile().mkdirs();f.createNewFile();}fos = new FileOutputStream(f);while ((bytesRead = eis.read(buffer)) != -1) {fos.write(buffer, 0, bytesRead);}} finally {if (fos != null) {try {fos.close();} catch (IOException e) {// ignore}}}}}
}
Java代码
- /*
- * To change this template, choose Tools | Templates
- * and open the template in the editor.
- */
- package com.test;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.util.zip.ZipEntry;
- import java.util.zip.ZipOutputStream;
- /**
- *
- * @author eg
- */
- class ZipFolderHelper {
- private boolean includeInitialFolder;
- public ZipFolderHelper() {
- }
- public void setIncludeInitialFolder(boolean includeInitialFolder) {
- this.includeInitialFolder = includeInitialFolder;
- }
- public void process(File folderToZip, File destZip) throws Exception {
- if (destZip.exists()) {
- destZip.delete();
- }
- ZipOutputStream zip = null;
- FileOutputStream fileWriter = null;
- fileWriter = new FileOutputStream(destZip);
- zip = new ZipOutputStream(fileWriter);
- addFolderToZip("", folderToZip.getPath(), zip);
- zip.flush();
- zip.close();
- }
- private void addFileToZip(String path, String srcFile, ZipOutputStream zip)
- throws Exception {
- File folder = new File(srcFile);
- if (folder.isDirectory()) {
- addFolderToZip(path, srcFile, zip);
- } else {
- FileInputStream in = null;
- try {
- byte[] buf = new byte[1024];
- int len;
- in = new FileInputStream(srcFile);
- String zeName = path + "/" + folder.getName();
- if (!includeInitialFolder) {
- int idx = zeName.indexOf("/");
- zeName = zeName.substring(idx + 1);
- }
- zip.putNextEntry(new ZipEntry(zeName));
- while ((len = in.read(buf)) > 0) {
- zip.write(buf, 0, len);
- }
- } finally {
- if (in != null) {
- in.close();
- }
- }
- }
- }
- private void addFolderToZip(String path, String srcFolder,
- ZipOutputStream zip) throws Exception {
- File folder = new File(srcFolder);
- for (String fileName : folder.list()) {
- if (path.equals("")) {
- addFileToZip(folder.getName(), srcFolder + "/" + fileName, zip);
- } else {
- addFileToZip(path + "/" + folder.getName(), srcFolder + "/"
- + fileName, zip);
- }
- }
- }
- }
/** To change this template, choose Tools | Templates* and open the template in the editor.*/
package com.test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/*** * @author eg*/
class ZipFolderHelper {private boolean includeInitialFolder;public ZipFolderHelper() {}public void setIncludeInitialFolder(boolean includeInitialFolder) {this.includeInitialFolder = includeInitialFolder;}public void process(File folderToZip, File destZip) throws Exception {if (destZip.exists()) {destZip.delete();}ZipOutputStream zip = null;FileOutputStream fileWriter = null;fileWriter = new FileOutputStream(destZip);zip = new ZipOutputStream(fileWriter);addFolderToZip("", folderToZip.getPath(), zip);zip.flush();zip.close();}private void addFileToZip(String path, String srcFile, ZipOutputStream zip)throws Exception {File folder = new File(srcFile);if (folder.isDirectory()) {addFolderToZip(path, srcFile, zip);} else {FileInputStream in = null;try {byte[] buf = new byte[1024];int len;in = new FileInputStream(srcFile);String zeName = path + "/" + folder.getName();if (!includeInitialFolder) {int idx = zeName.indexOf("/");zeName = zeName.substring(idx + 1);}zip.putNextEntry(new ZipEntry(zeName));while ((len = in.read(buf)) > 0) {zip.write(buf, 0, len);}} finally {if (in != null) {in.close();}}}}private void addFolderToZip(String path, String srcFolder,ZipOutputStream zip) throws Exception {File folder = new File(srcFolder);for (String fileName : folder.list()) {if (path.equals("")) {addFileToZip(folder.getName(), srcFolder + "/" + fileName, zip);} else {addFileToZip(path + "/" + folder.getName(), srcFolder + "/"+ fileName, zip);}}}
}
Java代码
- package com.test;
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.io.IOException;
- import java.util.Map;
- import org.apachemons.io.FileUtils;
- import org.apachemons.lang3.StringUtils;
- /**
- *
- * @author eg
- */
- public class DocxTemplater {
- private File unzipFolder;
- private File contentXmlFile;
- private String placeholderBefore = "${";
- private String placeholderAfter = "}";
- private static final String PATH_TO_CONTENT = "word/document.xml";
- public DocxTemplater(String pathToDocx, String before, String after) {
- this(new File(pathToDocx), before, after);
- }
- public DocxTemplater(String pathToDocx) {
- this(new File(pathToDocx));
- }
- public DocxTemplater() {
- }
- public DocxTemplater(File unzipFolder) {
- this.unzipFolder = unzipFolder;
- }
- public DocxTemplater(File unzipFolder, String before, String after) {
- this.unzipFolder = unzipFolder;
- this.placeholderBefore = before;
- this.placeholderAfter = after;
- }
- public void process(String destDocx, Map<String, Object> params) {
- process(new File(destDocx), params);
- }
- private void setup(File destDocx) throws IOException {
- ZipHelper.unzip(destDocx, unzipFolder);
- contentXmlFile = new File(unzipFolder, PATH_TO_CONTENT);
- }
- public void process(File destDocx, Map<String, Object> params) {
- try {
- setup(destDocx);
- if (!unzipFolder.exists()) {
- unzipFolder.mkdir();
- }
- if (!contentXmlFile.exists()) {
- throw new FileNotFoundException(
- contentXmlFile.getAbsolutePath());
- }
- String template = FileUtils.readFileToString(contentXmlFile,
- "UTF-8");
- for (Map.Entry<String, Object> entry : params.entrySet()) {
- template = StringUtils.replace(template, placeholderBefore
- + entry.getKey() + placeholderAfter,
- String.valueOf(entry.getValue()));
- }
- String destDocxString = destDocx.getPath();
- String noExtPathString = destDocxString.substring(0,
- destDocxString.lastIndexOf("."))
- + "_bak";
- File noExtPath = new File(noExtPathString);
- destDocx.delete();
- FileUtils.deleteDirectory(noExtPath);
- FileUtils.copyDirectory(unzipFolder, noExtPath);
- FileUtils.writeStringToFile(new File(noExtPath, PATH_TO_CONTENT),
- template, "UTF-8");
- ZipHelper.zipFolder(noExtPath, destDocx, false);
- FileUtils.deleteDirectory(noExtPath);
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
- }
package com.test;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Map;
import org.apachemons.io.FileUtils;
import org.apachemons.lang3.StringUtils;
/*** * @author eg*/
public class DocxTemplater {private File unzipFolder;private File contentXmlFile;private String placeholderBefore = "${";private String placeholderAfter = "}";private static final String PATH_TO_CONTENT = "word/document.xml";public DocxTemplater(String pathToDocx, String before, String after) {this(new File(pathToDocx), before, after);}public DocxTemplater(String pathToDocx) {this(new File(pathToDocx));}public DocxTemplater() {}public DocxTemplater(File unzipFolder) {this.unzipFolder = unzipFolder;}public DocxTemplater(File unzipFolder, String before, String after) {this.unzipFolder = unzipFolder;this.placeholderBefore = before;this.placeholderAfter = after;}public void process(String destDocx, Map<String, Object> params) {process(new File(destDocx), params);}private void setup(File destDocx) throws IOException {ZipHelper.unzip(destDocx, unzipFolder);contentXmlFile = new File(unzipFolder, PATH_TO_CONTENT);}public void process(File destDocx, Map<String, Object> params) {try {setup(destDocx);if (!unzipFolder.exists()) {unzipFolder.mkdir();}if (!contentXmlFile.exists()) {throw new FileNotFoundException(contentXmlFile.getAbsolutePath());}String template = FileUtils.readFileToString(contentXmlFile,"UTF-8");for (Map.Entry<String, Object> entry : params.entrySet()) {template = StringUtils.replace(template, placeholderBefore+ entry.getKey() + placeholderAfter,String.valueOf(entry.getValue()));}String destDocxString = destDocx.getPath();String noExtPathString = destDocxString.substring(0,destDocxString.lastIndexOf("."))+ "_bak";File noExtPath = new File(noExtPathString);destDocx.delete();FileUtils.deleteDirectory(noExtPath);FileUtils.copyDirectory(unzipFolder, noExtPath);FileUtils.writeStringToFile(new File(noExtPath, PATH_TO_CONTENT),template, "UTF-8");ZipHelper.zipFolder(noExtPath, destDocx, false);FileUtils.deleteDirectory(noExtPath);} catch (Exception e) {throw new RuntimeException(e);}}
}
Java代码
- package com.test;
- import java.io.File;
- import java.util.HashMap;
- //例子来自Github,原地址忘了,代码被我改过一部分
- public class DocxTemplater_Test {
- public static void main(String[] args) {
- DocxTemplater templater = new DocxTemplater("f:/saveFile/temp/test_c");
- File f = new File(
- "f:/saveFile/temp/doc_template.docx");
- HashMap<String, Object> map = new HashMap<String, Object>();
- map.put("TITLE", "这是替换后的文档");
- map.put("XUHAO", "1");
- map.put("NAME", "梅花");
- map.put("NAME2", "杏花");
- map.put("WORD", "问世间情为何物");
- map.put("DATA", "2014-9-28");
- map.put("BOSS", "Github");
- templater.process(f, map);
- }
- }
package com.test;import java.io.File;
import java.util.HashMap;
//例子来自Github,原地址忘了,代码被我改过一部分
public class DocxTemplater_Test {public static void main(String[] args) {DocxTemplater templater = new DocxTemplater("f:/saveFile/temp/test_c");File f = new File("f:/saveFile/temp/doc_template.docx");HashMap<String, Object> map = new HashMap<String, Object>();map.put("TITLE", "这是替换后的文档");map.put("XUHAO", "1");map.put("NAME", "梅花");map.put("NAME2", "杏花");map.put("WORD", "问世间情为何物");map.put("DATA", "2014-9-28");map.put("BOSS", "Github");templater.process(f, map);}
}
效果如下:
缺点:页眉页尾没替换,除非自己替换header.xml和footer.xml中的变量,对表格无效,想要替换变量制作表格,可以搜索下iteye的博文,以前有哥们写过,其实就是拿到table,然后自己往里面塞数据。
全文完。
更多推荐
[简单]使用docx4j制作简单的word(2007)小结
发布评论