poi 操作 office文档

一直审核不通过,直接放码当个记录。。

Excel

/**
     * 测试excel
     * @return
     */
    public Result test5(){
        path = path == null?"D:/Users/upload":path;
        InputStream is = this.getClass().getResourceAsStream("/template/培训项目评估总结表(模板).xlsx");
        try (XSSFWorkbook workbook = new XSSFWorkbook(is);FileOutputStream out = new FileOutputStream(path + "/培训项目评估总结表" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy年MM月")) + ".xlsx");){
            Sheet sheet = workbook.getSheetAt(0);

            XSSFCellStyle cellStyle = workbook.createCellStyle();
            XSSFColor xssfColor = new XSSFColor(Color.BLACK,new DefaultIndexedColorMap());
            cellStyle.setBorderColor(XSSFCellBorder.BorderSide.BOTTOM, xssfColor);
            cellStyle.setBorderBottom(BorderStyle.THIN);
            cellStyle.setBorderColor(XSSFCellBorder.BorderSide.TOP, xssfColor);
            cellStyle.setBorderTop(BorderStyle.THIN);
            cellStyle.setBorderColor(XSSFCellBorder.BorderSide.LEFT, xssfColor);
            cellStyle.setBorderLeft(BorderStyle.THIN);
            cellStyle.setBorderColor(XSSFCellBorder.BorderSide.RIGHT, xssfColor);
            cellStyle.setBorderRight(BorderStyle.THIN);
            cellStyle.setAlignment(HorizontalAlignment.CENTER);
            cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
            Font font = workbook.createFont();
            font.setBold(true);
            cellStyle.setFont(font);

            Row row = sheet.getRow(0);
            Cell cell = row.getCell(0);
            cell.setCellValue(getValue(cell).toString().replace("xxxx","测试项目"));
            int indexRow = 9;
            for (;indexRow < 100;indexRow++) {
                sheet.shiftRows(indexRow, sheet.getLastRowNum(), 1, true, false);
                createRowCells(sheet.createRow(indexRow), (short) 500, cellStyle, 123, 2323, "", 2332, "", 233, "", 23232);
            }
//            createRowCells(sheet.createRow(indexRow++),(short) 500,cellStyle,1234,2323,"",2332,"",233,"",23232);

            workbook.write(out);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {

        }
        return null;
    }

word

@Value("${upload.dir.filePath}")
private String path;

public static void main(String[] args) {
    new BaseDdDzFileService().test3();
}

public Result test3(){
        path = path == null?"D:/Users/upload":path;
        try (FileOutputStream out = new FileOutputStream(path + "/专项培训方案" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy年MM月")) + ".docx")){
            //创建文档对象
            InputStream inputStream = new FileInputStream(path + "/template/培训策划方案(模板)2.docx");
            XWPFDocument document = new XWPFDocument(inputStream);
            //替换对象
            HashMap<String,Object> data = new HashMap<>();

            List<XWPFTable> tables = document.getTables();
            //处理第一个表格
            XWPFTable table = tables.get(0);
            List<XWPFTableRow> rows = table.getRows();
            for(int i = 0;i < rows.size();i++){
                XWPFTableCell cell1 = rows.get(i).getCell(0);
                if(Pattern.matches("\\{\\{.*?\\}\\}",cell1.getText())){
                    CellStyle cellStyle = new CellStyle();
                    //设置单元格背景色
                    cellStyle.setBackgroundColor("FBE4D5");
                    ParagraphStyle paragraphStyle = new ParagraphStyle();
                    cellStyle.setDefaultParagraphStyle(paragraphStyle);
                    //创建单元格
                    createRowCells(table.createRow(),600,cellStyle,"16\n号","123","123","123","1233");
                    createRowCells(table.createRow(),600,cellStyle,"16\n号","123","123","123","1233");

                    //合并单元格
//                    mergeCellsVertically(table,0,3,4);
                    //删除模版行
                    table.removeRow(i);
                }
            }

            //复制表格测试代码
//            table = tables.get(1);
//            CTTbl ctTbl = CTTbl.Factory.newInstance(); // 创建新的 CTTbl , table
//            ctTbl.set(document.getTables().get(1).getCTTbl()); // 复制原来的CTTbl
//            IBody iBody = document.getTables().get(1).getBody();
//            BeanUtils.copyProperties(document.getTables().get(1).getBody(), iBody);
//            XWPFTable newTable = new XWPFTable(ctTbl,iBody);
//            document.createTable(); // 创建一个空的Table
//            document.setTable(2,newTable);

            //替换模版中的字符
            render(data,document);
            document.write(out);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
}

/**
* 批量创建段落单元格
* @param row 表格行
* @param rowHeight 行高
* @param cellStyle 单元格样式
* @param args 单元格内容
*/
public void createRowCells(XWPFTableRow row,Integer rowHeight, CellStyle cellStyle,String... args){
    XWPFTableCell cell;
    row.setHeight(rowHeight);
    for(int i = 0;i < args.length;i++){
        if (i == 0)
            cell = row.getCell(0);
        else
            cell = row.createCell();
        cell.setColor(cellStyle.getBackgroundColor());
        //默认垂直居中
        cell.setVerticalAlignment(cellStyle.getVertAlign() == null?XWPFTableCell.XWPFVertAlign.CENTER:cellStyle.getVertAlign());
        //默认取第一个段落
        XWPFParagraph xwpfParagraph = cell.getParagraphArray(0);
        xwpfParagraph.createRun().setText(args[i]);
        //默认水平居中
        xwpfParagraph.setAlignment(cellStyle.getDefaultParagraphStyle().getAlign() == null?ParagraphAlignment.CENTER:cellStyle.getDefaultParagraphStyle().getAlign());
    }
}

// word跨列合并单元格
public  void mergeCellsHorizontal(XWPFTable table, int row, int fromCell, int toCell) {
    for (int cellIndex = fromCell; cellIndex <= toCell; cellIndex++) {
        XWPFTableCell cell = table.getRow(row).getCell(cellIndex);
        if ( cellIndex == fromCell ) {
            // The first merged cell is set with RESTART merge value
            cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);
        } else {
            // Cells which join (merge) the first one, are set with CONTINUE
            cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE);
        }
    }
}

// word跨行并单元格
public void mergeCellsVertically(XWPFTable table, int col, int fromRow, int toRow) {
    for (int rowIndex = fromRow; rowIndex <= toRow; rowIndex++) {
        XWPFTableCell cell = table.getRow(rowIndex).getCell(col);
        if ( rowIndex == fromRow ) {
            // The first merged cell is set with RESTART merge value
            cell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.RESTART);
        } else {
            // Cells which join (merge) the first one, are set with CONTINUE
            cell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.CONTINUE);
        }
    }
}

/**
* 自动生成模版(仿tl)
* @param data  键值对数据
* @param document  文档对象
*/
public void render(Map<String,Object> data,XWPFDocument document){
    List<XWPFParagraph> xwpfParas = document.getParagraphs();
    //遍历段落
    for(int i = 0;i < xwpfParas.size();i++){
        //遍历单行
        XWPFParagraph xwpfParagraph = xwpfParas.get(i);
        //获取段落内容
        String text = xwpfParagraph.getText();
        if(Pattern.matches(".*\\{\\{.*?\\}\\}.*", text)) {
            List<XWPFRun> runs = xwpfParagraph.getRuns();
            StringBuffer flag = new StringBuffer();
            List<XWPFRun> eruns = new ArrayList<>();
            for(int j = 0;j < runs.size();j++){
                XWPFRun item = runs.get(j);
                //遍历run对象
                for (int poi = 0; poi < item.getCTR().sizeOfTArray(); poi++) {
                    if(item.getText(poi).indexOf("{") > -1 || !(flag.toString().equals(""))){
                        do{
                            flag.append(item.getText(poi));
                            eruns.add(item);
                            poi++;
                        }while (!Pattern.matches(".*\\{\\{.*?\\}\\}.*", flag.toString()) && poi < item.getCTR().sizeOfTArray());

                        //匹配{
   
   {*}}格式的字符串
                        if (Pattern.matches("\\{\\{.*?\\}\\}", flag.toString())) {
                            String key = flag.toString().substring((flag.toString().indexOf("{
   
   {") + 2),(flag.toString().indexOf("}}")));
                            flag = new StringBuffer();
                            Object value = data.get(key);
                            if (value != null) {
                                for (int m = 0;m < eruns.size();m++){
                                    if (m == (eruns.size() - 1)){
                                        String[] values = value.toString().indexOf("\n") > -1?value.toString().split("\\n"):new String[]{value.toString()};
                                        //根据反斜杠执行换行
                                        for(int n = 0;n < values.length;n++){
                                            eruns.get(m).setText(values[n], n);
                                            if(n != (values.length - 1))
                                                eruns.get(m).addCarriageReturn();
                                        }
                                    }else {
                                        eruns.get(m).setText("",0);
                                    }
                                }
                                eruns = new ArrayList<>();
                            }
                        }
                    }
                }
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_16253859/article/details/118399412