Word导出+表格
jar包
<dependency>
<groupId>com.deepoove</groupId>
<artifactId>poi-tl</artifactId>
<version>1.7.3</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
demo
@GetMapping("/exportUserWord")
@ApiOperation("test")
public void exportUserWord(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;filename=" + new SimpleDateFormat("yyyyMMddHHmm").format(new Date()) + ".docx");
List<Map<String, Object>> detailList = new ArrayList<Map<String, Object>>();
for (int i = 0; i < 6; i++) {
Map<String, Object> params = new HashMap<>();
params.put("name", "张三");
params.put("sex", "男");
params.put("mobile", "18888888888");
detailList.add(params);
}
// 渲染文本
String templatePath = "C:\\Users\\18132\\Desktop\\template.docx";
// ClassPathResource classPathResource = new ClassPathResource(templatePath);
// String resource = classPathResource.getURL().getPath();
HackLoopTableRenderPolicy policy = new HackLoopTableRenderPolicy();
Configure config = Configure.newBuilder().bind("detailList", policy).bind("detailList", policy).build();
// 渲染图片
// TODO 渲染其他类型的数据请参考官方文档
XWPFTemplate template = XWPFTemplate.compile(templatePath, config).render(
new HashMap<String, Object>() {{
put("detailList", detailList);
put("other", "我是其它信息");
}}
);
WordUtil.downloadWord(response.getOutputStream(), templatePath, template);
}
template.docx
结果
WordUtil
import com.deepoove.poi.XWPFTemplate;
import java.io.File;
import java.io.OutputStream;
import java.util.Date;
/**
* word工具类
* Poi-tl模板引擎官方文档:http://deepoove.com/poi-tl/
*/
public class WordUtil {
/**
* 根据模板填充内容生成word,并下载
*
* @param templatePath word模板文件路径
* @param xwpfTemplate 渲染数据
*/
public static void downloadWord(OutputStream out, String templatePath, XWPFTemplate xwpfTemplate) {
Long time = new Date().getTime();
// 生成的word格式
String formatSuffix = ".docx";
// 拼接后的文件名
String fileName = time + formatSuffix;
//设置生成的文件存放路径,可以存放在你想要指定的路径里面
String rootPath = "C:\\";
String filePath = rootPath + fileName;
File newFile = new File(filePath);
//判断目标文件所在目录是否存在
if (!newFile.getParentFile().exists()) {
//如果目标文件所在的目录不存在,则创建父目录
newFile.getParentFile().mkdirs();
}
// 读取模板templatePath并将paramMap的内容填充进模板,即编辑模板(compile)+渲染数据(render)
try {
//out = new FileOutputStream(filePath);//输出路径(下载到指定路径)
// 将填充之后的模板写入filePath
xwpfTemplate.write(out);//将template写到OutputStream中
out.flush();
out.close();
xwpfTemplate.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}