1.引入依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.14</version>
</dependency>
2.实现层代码
@GetMapping("downloadWord")
public void downloadWord(HttpServletRequest request,HttpServletResponse response){
try {
// 标题
String title = "测试标题";
// 内容
String text = "测试内容";
//富文本内容
String content="<html><body>" +
"<p style=\"text-align: center;\"><span style=\"font-family: 黑体, SimHei; font-size: 24px;\">"
+ title + "</span></p>" + text + "</body></html>";
//这里是必须要设置编码的,不然导出中文就会乱码。
byte b[] = content.getBytes("GBK");
//将字节数组包装到流中
ByteArrayInputStream bais = new ByteArrayInputStream(b);
/**
* 关键地方
* 生成word格式
*/
POIFSFileSystem poifs = new POIFSFileSystem();
DirectoryEntry directory = poifs.getRoot();
directory.createDocument("WordDocument", bais);
/**
* 方式一:创建文件并将流输出到文件中
*/
FileCopyUtils.copy(poifs.createDocumentInputStream("WordDocument"),new FileOutputStream("d:/test.doc"));
/**
* 方式二:直接输出流文件下载
*/
request.setCharacterEncoding("utf-8");
response.setContentType("application/msword");//导出word格式
response.addHeader("Content-Disposition", "attachment;filename=" +
new String(title.getBytes("GB2312"),"iso8859-1") + ".doc");
ServletOutputStream ostream = response.getOutputStream();
poifs.writeFilesystem(ostream);
bais.close();
ostream.close();
poifs.close();
}catch(Exception e){
e.printStackTrace();
}
}