赞
踩
public static void main(String[] args) {
//模板、文件、图片路径
String workPath=System.getProperty("user.dir") + "/static-utils/src/main/resources/word/";
String templateName="test.docx";
Map datas = new HashMap() {
{
//文本
put("name","xiaoguo");
put("sex","男");
put("year","20200105");
put("hello","xiaoguo写于2020年一月");
//自定义表格
RowRenderData header = RowRenderData.build(new TextRenderData("1C86EE", "姓名"), new TextRenderData("1C86EE", "学历"));
RowRenderData row0 = RowRenderData.build("张三", "研究生");
RowRenderData row1 = RowRenderData.build("李四", "博士");
RowRenderData row2 = RowRenderData.build("王五", "博士后");
put("tables", new MiniTableRenderData(header, Arrays.asList(row0, row1, row2)));
//自定义有序列表
put("testText", new NumbericRenderData(NumbericRenderData.FMT_DECIMAL, new ArrayList() {
{
add(new TextRenderData("Plug-in grammar"));
add(new TextRenderData("Supports word text, header..."));
add(new TextRenderData("Not just templates, but also style templates"));
}
}));
//网落图片
put("picture", new PictureRenderData(200, 150, ".jpg", BytePictureUtils.getUrlBufferedImage("https://gss3.bdstatic.com/7Po3dSag_xI4khGkpoWK1HF6hhy/baike/c0%3Dbaike116%2C5%2C5%2C116%2C38/sign=61c551093f6d55fbd1cb7e740c4b242f/d8f9d72a6059252d937820d3369b033b5ab5b9fd.jpg")));
//本地图片
put("picture2", new PictureRenderData(200, 150, ".jpg", BytePictureUtils.getLocalByteArray(new File(workPath + "c1.jpg"))));
}
};
generateWord(datas, workPath + templateName, workPath);
}
/**
* 通过word模板并生成word文档
*
* @param paramData 参数数据
* @param templatePath word模板地址加模板文件名字
* @param outFilePath 输出文件地址(不带文件名字)
* @return 生成的word文件
*/
public static File generateWord(Map paramData, String templatePath, String outFilePath) {
String outFileName = "word_" + System.currentTimeMillis() + "_" + random.nextInt(100) + ".doc";
return generateWord(paramData, templatePath, outFilePath, outFileName);
}
/**
* 通过word模板并生成word文档
*
* @param paramData 参数数据
* @param templatePath word模板地址加模板文件名字
* @param outFilePath 输出文件地址(不带文件名字)
* @param outFileName 输出文件名字
* @return 生成的word文件
*/
public static File generateWord(Map paramData, String templatePath, String outFilePath, String outFileName) {
//判断输出文件路径和文件名是否含有指定后缀
outFilePath = CommonUtil.addIfNoSuffix(outFilePath, "/", "\\");
outFileName = CommonUtil.addIfNoSuffix(outFileName, ".doc", ".docx");
//解析word模板
XWPFTemplate template = XWPFTemplate.compile(templatePath).render(paramData);
//输出文件
FileOutputStream out = null;
File outFile = new File(outFilePath + outFileName);
try {
out = new FileOutputStream(outFile);
template.write(out);
out.flush();
} catch (IOException e) {
log.error("生成word写入文件失败", e);
} finally {
if (template != null) {
try {
template.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return outFile;
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。