`
53873039oycg
  • 浏览: 824945 次
  • 性别: Icon_minigender_1
社区版块
存档分类
最新评论

[简单]使用docx4j制作简单的word(2007)小结

 
阅读更多

         如果在使用docx4j的过程中有一些效果自己不会写,上网也没搜索到答案,怎么解决呢
         可以把word 2007解压,word 2007解压后是很多xml,docx4j的sample例子上面有解压word的代码,如下

        

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import org.apache.commons.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);
		}
	}
}

   里面的内容为

   

     

       和excel 2007解压的内容差不多

       word内容在document.xml,页眉页脚在header.xml和footer.xml中,想要什么效果粗暴点就是把xml内容替换掉,后面会讲到这方面的内容,也可以这样做,先把原word解压一份,在word上面添加自己想要的效果,在解压,对比2份文件对应的xml内容就知道要修改那些类了,如下
    

      想要好看点就先格式化xml,如下

     

      图中就是设置页眉底部的边框xml代码部分,位置在p-->ppr->pbdr下面,名字叫between,相应的代码可以这么写:

    

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.apache.commons.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.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);
			}
		}
	}
}

 

package com.test;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Map;
import org.apache.commons.io.FileUtils;
import org.apache.commons.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.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,然后自己往里面塞数据
     全文完
 

 

  • 大小: 227.1 KB
  • 大小: 189.8 KB
  • 大小: 23.4 KB
  • 大小: 27.5 KB
  • 大小: 32.7 KB
  • 大小: 33 KB
0
0
分享到:
评论

相关推荐

    使用docx4j 技术操作word的读写

    使用docx4J技术操作word的读写,使用docx4J技术操作word的读写,

    docx4j操作word

    docx4j操作word,主要使用docx4j对word进行操作,比如chart图表、标签替换、目录等。

    docx4j生成word文档

    最近在做一个出卷系统,需要通过试卷模板从数据库中抽取题目,然后按照模板的样式生成完整的试卷,包括试卷格式的排版和图片的写入。这是用docx4j生成word文档。里面包括完整代码和所需jar包。

    docx4j操作word2007

    docx4j操作word2007

    用docx4j操作word书签,在word书签中插入文本

    用docx4j,jar出去word书签,在word书签中插入文本 源码可以通过以下链接查看: https://github.com/xulp-mzl/xlp-core https://github.com/xulp-mzl/xlp-third ...实例: public static void main(String[] args) ...

    docx4j根据书签替换word中的内容

    这是一段用docx4j根据书签替换word文档中的内容的代码,研究了一段时间,而且下了很多东西,希望有点用

    docx4j-3.3.5-API文档-中英对照版.zip

    赠送jar包:docx4j-3.3.5.jar; 赠送原API文档:docx4j-3.3.5-javadoc.jar; 赠送源代码:docx4j-3.3.5-sources.jar; 赠送Maven依赖信息文件:docx4j-3.3.5.pom; 包含翻译后的API文档:docx4j-3.3.5-javadoc-API...

    docx4j-3.3.5-API文档-中文版.zip

    赠送jar包:docx4j-3.3.5.jar; 赠送原API文档:docx4j-3.3.5-javadoc.jar; 赠送源代码:docx4j-3.3.5-sources.jar; 赠送Maven依赖信息文件:docx4j-3.3.5.pom; 包含翻译后的API文档:docx4j-3.3.5-javadoc-API...

    docx4j所需jar包全

    docx4j所需jar包整合,其中word转pdf,word转html,word中docx转doc,java代码实现,都可以使用,仅限学习参考使用。

    docx4j及其依赖包

    docx4j支持操作后缀.docx得word文档,替换书签,获取文档内容,稳定资源

    Docx4j是Java操作office2007+中的Word、Excel、PPT的开源项目

    Docx4j是Java操作office2007+中的Word、Excel、PPT的开源项目,其主要针对WordXML 同时也可以处理Excel和PPT,比POI要强大很多 . Docx4J基于开源协议ASLv2。 ASL是一个广泛适用于社区开源软件并被开源业界所认可的...

    DOCX4J jar包

    docx4j 用的jar包,docx4j学习网址:http://www.docx4java.org/trac/docx4j

    word转pdf所用docx4j

    docx4j 用的jar包,docx4j学习网址:http://www.docx4java.org/trac/docx4j

    docx4j word合并转pdf.zip

    使用docx4j相关jar包,实现多个word文档合并,并转为pdf文档格式

    使用docx4j将图片签名插入到word中书签位置

    压缩包里包含了必要的docx4j.jar、commons-io-1.4.jar、slf4j-api-1.7.17.jar、freemrkker.jar等架包,导入到到项目后重新build path,然后运行InsertPicture.java文件,(ps:文件的参数替换成自己本地的),便可以...

    利用docx4j实现docx转pdf

    利用docx4j实现docx转pdf小dome

    最新 docx4j-master

    最新 docx4j-master最新 docx4j-master最新 docx4j-master最新 docx4j-master最新 docx4j-master最新 docx4j-master最新 docx4j-master最新 docx4j-master最新 docx4j-master最新 docx4j-master最新 docx4j-master...

    docx4j api

    docx4j api 帮助文档 word导出必备 学习必备

    java实现word合并(poi,jacob,docx4j,plutext)及文件格式转换全家桶

    word合并全家桶,包括横页和竖页兼容合并,里面包含使用文件格式转换,rtf转换为标准的word格式或者其他类型转换,jacob合并word案例及jar包,docx4j合并word案例及jar包,还有poi合并,以及Plutext-Enterprise-3.3.0.6...

Global site tag (gtag.js) - Google Analytics