poi操作word

/**
 * 动态填充word
 */
@Component
public class ToDocUtils {
    //使用示例
    /**
     * 导出docx
     *
     * @param wesInfoService
     * @param templatePath
     * @param outPath
     * @param map
     */
    public static boolean  getDocx(WesInfoServiceImpl wesInfoService, String templatePath, String outPath, Map<String, String> map, String familyNum, List<UnionFilter> list, List<UnionFilter> list1, List<UnionFilter> list2, List<QualityControlData> list3, HttpServletRequest request, HttpServletResponse response, InspectionReport report, List<OmimData> omimDatas){
        XWPFDocument document = null;
        try{
            File file = new File(templatePath);
            InputStream in = new FileInputStream(file);
            document = new XWPFDocument(in);
            //获取表格对象集合
            List<XWPFTable> tables = document.getTables();
            insertTable3(document,tables.get(4),list3,omimDatas); //质控表
            Iterator<XWPFHeader> headerIterator = document.getHeaderList().iterator();
            while (headerIterator.hasNext()){
                XWPFHeader header = headerIterator.next();
                List<XWPFParagraph> paragraphs = header.getParagraphs();
                for (XWPFParagraph paragraph : paragraphs) {
                    List<XWPFRun> runs = paragraph.getRuns();
                    for (XWPFRun run : runs) {
                        String text = run.getText(0);
                        if (text != null && text.contains("医院LOGO")) {
                            int index = text.indexOf("医院LOGO");
                            run.setText("",index);
                            // 插入新的图片
                            InputStream imgStream = new FileInputStream("src/main/resources/templates/head1.png");
                            run.addPicture(imgStream, XWPFDocument.PICTURE_TYPE_PNG, "src/main/resources/templates/head1.png", Units.toEMU(75), Units.toEMU(65));
                        }
                        if(text!=null&&text.contains("proband_NO")){
                            int index = text.indexOf("proband_NO");
                            run.setText(map.get("proband_NO"),index);
                        }
                        if(text!=null&&text.contains("proband_name")){
                            int index = text.indexOf("proband_name");
                            run.setText(map.get("proband_name"),index);
                        }
                    }
                }
            }
            Iterator<XWPFFooter> footerIterator = document.getFooterList().iterator();
            while (footerIterator.hasNext()){
                XWPFFooter footer = footerIterator.next();
                List<XWPFParagraph> paragraphs = footer.getParagraphs();
                for (XWPFParagraph paragraph : paragraphs) {
//                paragraph.setAlignment(ParagraphAlignment.LEFT);
                    replaceParagraph(paragraph,map);
                }
            }
            replaceInTable(document,map);  //替换表格里面的变量
            //替换段落里的
            for (XWPFParagraph paragraph : document.getParagraphs()) {
                replaceParagraph(paragraph, map);
            }
            // 如果文件夹不存在 则建立新文件夹
            File dir= new File(outPath);
            if (!!dir.exists()) {
                dir.mkdirs();
            }
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            OutputStream out = new FileOutputStream(outPath);
            document.write(bos);
            out.write(bos.toByteArray());
            FileInputStream inputStream = new FileInputStream(dir);
            XWPFDocument xwpfDocument = new XWPFDocument(inputStream);
            List<XWPFTable> xwpftables = xwpfDocument.getTables();
            for (int i = 1; i < xwpftables.size(); i++) {
                for (int i1 = 1; i1 < xwpftables.get(i).getRows().size(); i1++) {
                    for (int i2 = 0; i2 < xwpftables.get(i).getRows().get(i1).getTableCells().size(); i2++) {
                        if(xwpftables.get(i).getRows().get(i1).getTableCells().get(i2).getParagraphs().get(0).getRuns().size()==0){
                            continue;
                        }
                        for (XWPFParagraph paragraph : xwpftables.get(i).getRows().get(i1).getTableCells().get(i2).getParagraphs()) {
                            for (XWPFRun run : paragraph.getRuns()) {
                                **run.setFontSize(8);**
                            }
                        }
                    }
                }
            }

            ByteArrayOutputStream bos1 = new ByteArrayOutputStream();
            OutputStream out1 = new FileOutputStream(outPath);
            xwpfDocument.write(bos1);
            out1.write(bos1.toByteArray());
            InputStream fis1 = new BufferedInputStream(new FileInputStream(outPath));
            response.reset();//重置 响应头
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/msword");//告知浏览器下载文件,而不是直接打开,浏览器默认为打开
            response.setHeader(CONTENT_DISPOSITION, "attachment;filename=" +  URLEncoder.encode(familyNum+report.getName()+".doc", "UTF-8"));
            byte[] b1 = new byte[1024];
            int len1;
            while ((len1 = fis1.read(b1)) > 0){
                response.getOutputStream().write(b1, 0, len1);
            }
            return true;
        }
        catch (Exception e){
            e.printStackTrace();
            return false;
        } finally{
            try
            {
                if ( document != null )
                {
                    document.close();
                }
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }

    /**
     * 表格质控
     * @param document
     * @param table
     * @param tableList
     * @param omimDatas
     */
    public static void insertTable3(XWPFDocument document,XWPFTable table, List<QualityControlData> tableList,List<OmimData> omimDatas){
        //创建行,根据需要插入的数据添加新行c,不处理表头
        //判断需要插入的数量
        if (tableList.size() > 3) {//我的模板预留了1行
            for (int i=0;i<tableList.size()-3;i++) {
                insertRow(table,2 ,4+i);
            }
        }
        //遍历表格插入数据
        List<XWPFTableRow> rows = table.getRows();
        for(int i = 1; i < tableList.size() + 1; i++){
            XWPFTableRow newRow = table.getRow(i);
            List<XWPFTableCell> cells = newRow.getTableCells();
            QualityControlData data = tableList.get(i - 1);
            cells.get(1).setText(data.getName());
            cells.get(0).setText(data.getLabNum());
            cells.get(2).setText(data.getFamilyRelationship());
            cells.get(3).setText(String.valueOf(data.getSequencingDepth()));
            cells.get(4).setText(data.getTenXCoverage());
            cells.get(5).setText(data.getTwentyXConverage());
        }

    }

  
    /**
     * insertRow 在word表格中指定位置插入一行,并将某一行的样式复制到新增行
     * @param copyrowIndex 需要复制的行位置
     * @param newrowIndex 需要新增一行的位置
     * */
    public static void insertRow(XWPFTable table, int copyrowIndex, int newrowIndex) {
        // 在表格中指定的位置新增一行
        XWPFTableRow targetRow = table.insertNewTableRow(newrowIndex);
        // 获取需要复制行对象
        XWPFTableRow copyRow = table.getRow(copyrowIndex);
        //复制行对象
        targetRow.getCtRow().setTrPr(copyRow.getCtRow().getTrPr());
        //或许需要复制的行的列
        List<XWPFTableCell> copyCells = copyRow.getTableCells();
        //复制列对象
        XWPFTableCell targetCell = null;
        for (XWPFTableCell copyCell : copyCells) {
            targetCell = targetRow.addNewTableCell();
            targetCell.getCTTc().setTcPr(copyCell.getCTTc().getTcPr());
            if (copyCell.getParagraphs() != null && copyCell.getParagraphs().size() > 0) {
                targetCell.getParagraphs().get(0).getCTP().setPPr(copyCell.getParagraphs().get(0).getCTP().getPPr());
                if (copyCell.getParagraphs().get(0).getRuns() != null
                        && copyCell.getParagraphs().get(0).getRuns().size() > 0) {
                    XWPFRun cellR = targetCell.getParagraphs().get(0).createRun();
                    cellR.setBold(copyCell.getParagraphs().get(0).getRuns().get(0).isBold());
                }
            }
        }

    }

    /**
     * 正则匹配字符串
     *
     * @param str
     * @return
     */
    private static Matcher matcher(String str) {
        Pattern pattern = Pattern.compile("\\$\\{(.+?)\\}", Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(str);
        return matcher;
    }

    /**
     * 替换段落里面的变量
     * @param paragraph
     * @param map
     */
    public static void replaceParagraph(XWPFParagraph paragraph, Map<String, String> map){
        List<XWPFRun> runs;
        Matcher matcher;
        String runText = "";

        if (matcher(paragraph.getParagraphText()).find()) {
            runs = paragraph.getRuns();
            int j = runs.size();
            for (int i = 0; i < j; i++) {
                runText += runs.get(0).toString();
                //保留最后一个段落,在这段落中替换值,保留段落样式
                if (!((j - 1) == i)) {
                    paragraph.removeRun(0);
                }
            }
            matcher = matcher(runText);
            if (matcher.find()) {
                while ((matcher = matcher(runText)).find()) {
                    runText = matcher.replaceFirst(String.valueOf(map.get(matcher.group(1))));
                }
                runs.get(0).setText(runText, 0);
            }
        }

      }

    /**
     * 替换表格里面的变量
     * @param document
     * @param map
     */
    public static void replaceInTable(XWPFDocument document, Map<String, String> map) throws Exception {
        Iterator<XWPFTable> iterator = document.getTablesIterator();
        while (iterator.hasNext()){
            //获取表
            XWPFTable table = iterator.next();
            //获取行
            List<XWPFTableRow> rows = table.getRows();

            for (XWPFTableRow row : rows) {
                //获取单元格
                List<XWPFTableCell> cells = row.getTableCells();
                for (XWPFTableCell cell : cells) {
                    List<XWPFParagraph> paragraphs = cell.getParagraphs();
                    for (XWPFParagraph paragraph : paragraphs) {
                        replaceParagraph(paragraph,map);
                        **paragraph.setAlignment(ParagraphAlignment.CENTER);**

                    }
                }
            }
        }
    }



}

你可能感兴趣的:(word,windows)