公司中要做一些导出word的工作,经别人推荐,使用了Aspose.Words for Java ,感觉很好用,美中不足的地方就是,它是收费软件。
原理吗?比较常规,模板+入参==》aspose引擎==》生成文档。
在里,给大家提供一个简单的DEMO:
1、Maven依赖:
com.aspose
aspose-words
14.9.0
jdk16
2、word模板:
![Aspose.Words for Java 体验](https://img.it610.com/image/info8/599badeb818d485fb46852f1010d1ba9.png)
文章图片
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 datas) {if (isLicense) {
try {
Document doc = new Document(input);
// 遍历要替换的内容
Iterator keys = datas.keySet().iterator();
while (keys.hasNext()) {
String key = keys.next();
String value = https://www.it610.com/article/String.valueOf(datas.get(key));
// 对显示值得修改
if (Tool.isNull(value)) {
value ="";
}
value = https://www.it610.com/article/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 datas = new HashMap();
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、结果
![Aspose.Words for Java 体验](https://img.it610.com/image/info8/16f31d5e5c0b487d971e6e35a5c4c24e.png)
文章图片
很简单,很强大。简单的东西一般都很强大。
想生成和操作内容复杂的word文档,请去参看官网,导出word,推荐使用Aspose.Words。
【Aspose.Words for Java 体验】
推荐阅读
- Python|Python实战(使用线性回归预测房价)
- python|requests库请求获取不到数据怎么办(不妨试试看这种妙法)
- paas开发平台|GForms展现服务云开发平台
- 解决php网页运行超时问题:Maximum execution time of 30 seconds exceeded
- JavaEE开发|Java EE 8的五大新特性详解
- Web开发|FastJSON 简介及其Map/JSON/String 互转
- Web开发|解决WampServer服务器离线问题
- 服务器|怎样配置apache虚拟主机
- PythonWeb_Django(1)
- 多线程练习-两个线程交替打印