最近项目涉及到一个功能需求:将指定文本写入word文档,并根据指定词语将word中内容改变颜色并下载。
用到的jar包:spire.doc.jar org.apache.poi
官网链接:https://www.e-iceblue.cn/Downloads/Free-Spire-Doc-JAVA.html
将jar包导入到项目中。以下是部分代码供参考:
/**
* 处理word并下载
* @param list 指定词语list
* @return
*/
@RequestMapping("handler_str")
public ResponseData handlerStringToDoc(List<String> list,HttpServletResponse response) throws IOException {
XWPFDocument document = new XWPFDocument();
OutputStream stream = null;
BufferedOutputStream bufferStream = null;
Document doc = new Document();
//读取word文档 并开始处理
doc.loadFromFile("/xxx/xxx/xxx.doc");
for(String s : list){
if(s!=null){
TextSelection[] textSelections = doc.findAllString(s, false, false);
//匹配相同词语 并修改为红色
for (TextSelection selection : textSelections) {
selection.getAsOneRange().getCharacterFormat().setTextColor(Color.RED);
}
}
}
//保存
doc.saveToFile("/xxx/xxx/xxx.doc", FileFormat.Docm_2013);
doc.dispose();
try {
InputStream is = new FileInputStream("/xxx/xxx/xxx.doc");
XWPFDocument document1 = new XWPFDocument(is);
//以上Spire.Doc 生成的文件会自带警告信息,这里来删除Spire.Doc 的警告
document1.removeBodyElement(0);
stream = new FileOutputStream(new File("/xxx/xxx/xxx.doc"));
bufferStream = new BufferedOutputStream(stream, 1024);
this.setResponseHeader(response,"/xxx/xxx/xxx.doc");
OutputStream os = response.getOutputStream();
document1.write(os);
os.flush();
os.close();
}catch (Exception e){
e.printStackTrace();
}finally {
stream.close();
bufferStream.close();
}
return ResponseData.success("success");
}
/**
* 向客户端发送响应流方法
*
* @param response
* @param fileName
*/
public void setResponseHeader(HttpServletResponse response, String fileName) {
try {
try {
fileName = new String(fileName.getBytes(), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
} catch (Exception ex) {
ex.printStackTrace();
}
}
有其他需求可以查看spire.doc的文档,还有很多操作word的方法,有兴趣的童鞋可以去看看。
文档链接:https://www.e-iceblue.cn/spiredocforjava/spire-doc-for-java-program-guide-content.html