使用spire.doc for java读取word文档中内容并根据指定内容修改word中字体颜色并下载


用到的jar包:spire.doc.jar        org.apache.poi

spire.doc下载:https://www.e-iceblue.cn/Downloads/Free-Spire-Doc-JAVA.html

 1 /**
 2      * 处理word并下载
 3      * @param list  指定词语list
 4      * @return
 5      */
 6     @RequestMapping("handler_str")
 7     public ResponseData handlerStringToDoc(List<String> list,HttpServletResponse response) throws IOException {
 8         XWPFDocument document = new XWPFDocument();
 9         OutputStream stream = null;
10         BufferedOutputStream bufferStream = null;
11         Document doc = new Document();
12         //读取word文档 并开始处理
13         doc.loadFromFile("/xxx/xxx/xxx.doc");
14         for(String s : list){
15             if(s!=null){
16                 TextSelection[] textSelections = doc.findAllString(s, false, false);
17                 //匹配相同词语 并修改为红色
18                 for (TextSelection selection : textSelections) {
19                     selection.getAsOneRange().getCharacterFormat().setTextColor(Color.RED);
20                 }
21             }
22         }
23         //保存
24         doc.saveToFile("/xxx/xxx/xxx.doc", FileFormat.Docm_2013);
25         doc.dispose();
26         try {
27             InputStream is = new FileInputStream("/xxx/xxx/xxx.doc");
28             XWPFDocument document1 = new XWPFDocument(is);
29             //以上Spire.Doc 生成的文件会自带警告信息,这里来删除Spire.Doc 的警告
30             document1.removeBodyElement(0);
31             stream = new FileOutputStream(new File("/xxx/xxx/xxx.doc"));
32             bufferStream = new BufferedOutputStream(stream, 1024);
33  
34             this.setResponseHeader(response,"/xxx/xxx/xxx.doc");
35             OutputStream os = response.getOutputStream();
36             document1.write(os);
37             os.flush();
38             os.close();
39         }catch (Exception e){
40             e.printStackTrace();
41         }finally {
42             stream.close();
43             bufferStream.close();
44         }
45         return ResponseData.success("success");
46     }
47 /**
48      * 向客户端发送响应流方法
49      *
50      * @param response
51      * @param fileName
52      */
53     public void setResponseHeader(HttpServletResponse response, String fileName) {
54         try {
55             try {
56                 fileName = new String(fileName.getBytes(), "UTF-8");
57             } catch (UnsupportedEncodingException e) {
58                 e.printStackTrace();
59             }
60             response.setContentType("application/vnd.ms-excel");
61             response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
62         } catch (Exception ex) {
63             ex.printStackTrace();
64         }
65     }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM