The operation of poi on word

    Because excle is a cell, the operation is very simple. Compared with it, the word operation is relatively complicated. The word operation is mainly used to replace the text content to realize the dynamic generation of the word. The following is my thought on this piece, And the operation is summarized.

    0. Like excle, there is an old version of the file format is doc format, the corresponding object name is HWPFDocument, and the object corresponding to the latest docx format is XWPFDocument, here is the latter example. Because the table is processed at work, the header is generally a line of description, such as the title, year, month, day, name, etc., and then the table content is filled in this form, so the following operations take this file content as an example of the processing object.

    1.XWPFDocument docx = new XWPFDocument(inputstream);// word is mainly instantiated by passing in the file stream.

    2.List<XWPFParagraph> allXWPFParagraphs = docx.getParagraphs(); Get a line of text paragraph data as an XWPFParagraph object.

        Traverse allXWPFParagraphs above -> for (XWPFParagraph xwpfParagraph : paragraphs)

       Through List<XWPFRun> run = xwpfParagraph.getRuns(); Get the text in the paragraph to end with symbols or different data types, just like a sentence will end with a period.

        Traverse the above utterance collection -> for (int i = 0; i < run.size(); i++)

        run.get(i).setText (the value to be set, where to start), replace a sentence

      3. Because I found a lot of examples on the Internet, it is not very easy to use, so I wrote a text conversion tool class at work to facilitate use. code show as below:

       /**
     * Export word (new)
     * @author Niu Muyuan
     * @param tempMap name replacement
     * @param tempFilePath read file path
     * @param response response
     * @param fileName download file name
     * @throws Exception
     */
    public void docxFileExport( Map<String, String> tempMap, String tempFilePath,
            HttpServletResponse response, String fileName) throws Exception {
        XWPFDocument docx = new XWPFDocument(new FileInputStream(tempFilePath));    
        List<XWPFParagraph> paragraphs = docx.getParagraphs();
        
        for (XWPFParagraph xwpfParagraph : paragraphs) {
            List<XWPFRun> run = xwpfParagraph.getRuns();
            for (int i = 0; i < run.size(); i++) {
                for (Map.Entry<String, String> entry : tempMap.entrySet()) {
                    String val = run.get(i).getText(run.get(i).getTextPosition());
                    if (val != null && val.equals(entry.getKey())) {
                        run.get(i).setText(entry.getValue(), 0);
                    }
                }
            }
        }
        
        // 美滋滋循环
        List<XWPFTable> tables = docx.getTables();
        for (XWPFTable table : tables) {
            List<XWPFTableRow> rows = table.getRows();
            for (XWPFTableRow row : rows) {
                List<XWPFTableCell> cells = row.getTableCells();
                for (XWPFTableCell cell : cells) {
                    List<XWPFParagraph> cellPara = cell.getParagraphs();
                    for (XWPFParagraph xwpfParagraph : cellPara) {
                        List<XWPFRun> run = xwpfParagraph.getRuns();
                        for (int i = 0; i < run.size(); i++) {
                            for (Map.Entry<String, String> entry : tempMap.entrySet()) {
                                String val = run.get(i).getText(run.get(i).getTextPosition());
                                if (val != null && val.equals(entry.getKey())) {
                                    run.get(i).setText(entry.getValue(), 0);
                                }
                            }
                        }
                    }
                }
            }
        }
        ByteArrayOutputStream os = new ByteArrayOutputStream();                
        docx.write(os);
        byte[] content = os.toByteArray();
        InputStream is = new ByteArrayInputStream(content);
        response.reset();
        response.setContentType("application/x-download;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename="
            + new String((fileName+ System.currentTimeMillis() + ".docx").getBytes(), "iso-8859-1"));
        response.setHeader("Set-Cookie", "fileDownload=true; path=/");
        ServletOutputStream out = response.getOutputStream();
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
          bis = new BufferedInputStream(is);
          bos = new BufferedOutputStream(out);
          byte[] buff = new byte[2048];
          int bytesRead;
          while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
            bos.write(buff, 0, bytesRead);
          }
        } catch (Exception e) {
          e.printStackTrace();
        } finally {
          if (bis != null)
            bis.close();
          if (bos != null)
            bos.close();
        }
    }

  4. The code is briefly explained for future reuse

     You need to set the word template yourself, and then set the part that needs to be added to any English combination such as nmy. Then set the map to be replaced, the key is the keyword to be replaced, the value is the content to be replaced, the method will finally pop up the download, response.setHeader("Set-Cookie", "fileDownload=true; path=/") ; Prevent multiple clicks to download, and finally pop up the download through the memory stream. In order to prevent garbled characters, set new String((fileName+ System.currentTimeMillis() + ".docx").getBytes(), "iso-8859-1")) and then it seems to be nothing. . .

     

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324931935&siteId=291194637