使用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