公司中要做一些导出word的工作,经别人推荐,使用了Aspose.Words for Java ,感觉很好用,美中不足的地方就是,它是收费软件。
原理吗?比较常规,模板+入参==》aspose引擎==》生成文档。
在里,给大家提供一个简单的DEMO:
1、Maven依赖:
- <dependency>
- <groupId>com.aspose</groupId>
- <artifactId>aspose-words</artifactId>
- <version>14.9.0</version>
- <classifier>jdk16</classifier>
- </dependency>
2、word模板:
3、把license文件放入classpath。如果没有license会有水印。如果不想购买,又想用,请自己想办法。
4、核心代码:
- import java.io.InputStream;
- import java.util.HashMap;
- import java.util.Iterator;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import com.aspose.words.Document;
- import com.aspose.words.License;
- import com.ths.platform.custom.util.Tool;
- public class RepDocTemplate {
- // 默认没有license,会有水印文字
- private boolean isLicense = false;
- // 初始化日志
- private static final Logger log = LoggerFactory
- .getLogger(RepDocTemplate.class);
- /**
- * 私有构造,用户初始化License
- */
- public RepDocTemplate() {
- InputStream is = RepDocTemplate.class.getClassLoader()
- .getResourceAsStream("license.xml");
- License aposeLic = new License();
- try {
- aposeLic.setLicense(is);
- isLicense = true;
- } catch (Exception e) {
- log.error("word模板破解失败!", e);
- }
- }
- /**
- * 替换内容的主要操作
- *
- * @param input
- * @param output
- * @param datas
- */
- public void replaceDocTem(String input, String output,
- HashMap<String, Object> datas) {
- if (isLicense) {
- try {
- Document doc = new Document(input);
- // 遍历要替换的内容
- Iterator<String> keys = datas.keySet().iterator();
- while (keys.hasNext()) {
- String key = keys.next();
- String value = String.valueOf(datas.get(key));
- // 对显示值得修改
- if (Tool.isNull(value)) {
- value = "";
- }
- value = value.replace("\r\n", " ");
- // 要求替换的内容是完全匹配时的替换
- doc.getRange().replace("$" + key + "$", value, true, false);
- }
- // 替换保存后的内容
- doc.save(output);
- } catch (Exception e) {
- log.error(e.getMessage(), e);
- }
- }
- }
- }
测试方法:
- public void export_word() {
- //准备数据,用于替换模板中的占位符
- //可以根据业务,从数据库中读取
- HashMap<String, Object> datas = new HashMap<String, Object>();
- datas.put("property_a", "helloworld_a");
- datas.put("property_b", "helloworld_b");
- datas.put("property_c", "helloworld_c");
- datas.put("property_d", "helloworld_d");
- datas.put("property_e", "helloworld_e");
- datas.put("property_f", "helloworld_f");
- datas.put("property_g", "helloworld_g");
- datas.put("property_h", "helloworld_h");
- datas.put("property_i", "helloworld_i");
- datas.put("property_j", "helloworld_j");
- datas.put("property_k", "helloworld_k");
- datas.put("property_l", "helloworld_l");
- datas.put("property_m", "helloworld_m");
- datas.put("property_n", "helloworld_n");
- datas.put("property_o", "helloworld_o");
- datas.put("property_p", "helloworld_p");
- datas.put("property_q", "helloworld_q");
- datas.put("property_r", "helloworld_r");
- String contextPath = request.getSession().getServletContext()
- .getRealPath("/");
- //模板文件名
- String docName="word_template.doc";
- //模板路径,示例写死饿,可以自行改为可配置的方式
- //String inPath = (PathUtil.webAppPath() + "/WEB-INF/office/word/").replace("/", File.separator)+ docName;
- String inPath = (contextPath + "solution/office/word/").replace("/", File.separator)+ docName;
- //生成word的名称
- String fileName = "word"+String.valueOf(System.currentTimeMillis())+".doc";
- //word生成路径
- String outPath = (contextPath + "solution/office/word-export/").replace("/", File.separator)+ fileName;
- InputStream in = null;
- OutputStream out = null;
- byte[] buf = new byte[1024];
- int len = 0;
- try {
- //传入参数,根据模板生成word
- RepDocTemplate doc = new RepDocTemplate();
- doc.replaceDocTem(inPath, outPath, datas);
- //下载生成的word
- in = new FileInputStream(new File(outPath));
- response.setContentType("application/x-download;charset=UTF-8");
- response.setHeader("Content-Disposition", "attachment; filename="
- + URLEncoder.encode(fileName, "utf-8"));
- out = response.getOutputStream();
- while ((len = in.read(buf)) > 0) {
- out.write(buf, 0, len);
- }
- in.close();
- out.flush();
- out.close();
- } catch (Exception e) {
- log.error(e.getMessage(), e);
- } finally {
- if (null != in) {
- try {
- in.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- if (null != out) {
- try {
- out.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }
5、结果
很简单,很强大。简单的东西一般都很强大。
想生成和操作内容复杂的word文档,请去参看官网,导出word,推荐使用Aspose.Words。