<!-- poi-tl word文档导出 -->
<dependency>
<groupId>com.deepoove</groupId>
<artifactId>poi-tl</artifactId>
<version>1.10.0</version>
</dependency>
工具类
import com.deepoove.poi.XWPFTemplate;
import org.springframework.util.ClassUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Map;
/**
* @ Author :星晨
* @ Description:工具类
*/
public class DocUtil {
public static void download(HttpServletRequest request, HttpServletResponse response, String newWordName, Map dataMap) {
String path = ClassUtils.getDefaultClassLoader().getResource("").getPath();
XWPFTemplate template = XWPFTemplate.compile(path+"static/templates/word.docx").render(dataMap);
OutputStream out = null;
try {
out = new FileOutputStream("out_template.docx");
template.write(out);
out.flush();
out.close();
template.close();
} catch (IOException e) {
e.printStackTrace();
}
InputStream fis = null;
OutputStream toClient = null;
File file = new File("out_template.docx");
try {
fis = new BufferedInputStream(new FileInputStream(file));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 清空response
response.reset();
// 设置response的Header
newWordName = URLEncoder.encode(newWordName, "utf-8"); //这里要用URLEncoder转下才能正确显示中文名称
response.addHeader("Content-Disposition", "attachment;filename=" + newWordName+"");
response.addHeader("Content-Length", "" + file.length());
toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
toClient.write(buffer);
toClient.flush();
} catch (Exception e) {
e.printStackTrace();
} finally{
try {
if(fis!=null){
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if(toClient!=null){
toClient.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
controller
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
* @ Author :星晨
* @ Description:
*/
@RestController
public class wordcontroller {
@RequestMapping("getDoc")
public void getDoc(HttpServletRequest request, HttpServletResponse response) throws IOException {
Map<String,String> dataMap = new HashMap<String,String>();
dataMap.put("workname", "单位名称");
dataMap.put("name1", "wuhui");
dataMap.put("name2", "azy");
dataMap.put("name3", "zyq");
dataMap.put("year", "2019");
dataMap.put("month", "08");
dataMap.put("day", "19");
String newWordName = "信息.doc";
//调用打印word的函数
DocUtil.download(request,response,newWordName, dataMap);
}
}