POI使用模板制作PPT,替换内容时原样式丢失问题的解决办法

通常会使用模板来制作PPT,模板中使用特定字符串表示待替换的内容,但是使用POI编辑PPT模板时会出现,内容被替换的同时,原本的样式也丢失。

不要使用TextShape和TableCell的setText进行内容替换

可以使用下面的方法, 只替换文本段落的内容

/**
* 打开模板文件进行替换
**/
private void replaceTemplate(String templateFile) {
    //打开PPT,并制定新文件
    try (SlideShow ppt = new XMLSlideShow(new FileInputStream(templateFile));
            FileOutputStream out = new FileOutputStream("newFile.pptx")){
        List slides = ppt.getSlides();
        for (Slide slide : slides) {
            List shapes = slide.getShapes();
            for (Shape shape : shapes) {
                if (shape instanceof TextShape) { //文本
                    List list = ((TextShape) shape).getTextParagraphs();           
                    replaceData(list);
                }
                if (shape instanceof TableShape) {// 表格
                    int rowSize = ((TableShape) shape).getNumberOfRows();
                    int columnSize = ((TableShape) shape).getNumberOfColumns();
                    for (int rowNum = 0; rowNum < rowSize; rowNum++) {
                        for (int columnNum = 0; columnNum < columnSize; columnNum++) {
                            TableCell cell = ((TableShape) shape).getCell(rowNum, columnNum);
                            if (cell != null) {
                                List list = cell.getTextParagraphs();
                                replaceData(list);
                            }
                        }
                    }
                }
            }
        }
        ppt.write(out);
    }catch (Exception e){
        e.printStackTrace();
    }
}
/**
* 寻找段落中的所有TextRun并进行替换工作
**/
private void replaceData(List list) {
    if(list == null || list.size() <= 0)
        return;
    for (TextParagraph textParagraph : list) {
        if(textParagraph == null)
            continue;
        List textRuns = textParagraph.getTextRuns();
        if(textRuns == null || textRuns.size() <= 0 || textRuns.isEmpty())
            continue;
        for (TextRun textRun : textRuns) {
            if(textRun == null)
                continue;
            replaceDate(textRun, "yyyy", "2018");
        }
    }
}
/**
* 把特定pat替换成新的value
**/
private void replaceData(TextRun textRun, String pat, value) {
    String text = textRun.getRawText();
    if(StringUtil.isNull(text))
        return;
    String r = text;
    if(r.contains(pat))
        r = r.replaceAll(pat, value);
    if(!r.equals(text))
        textRun.setText(r);

 

你可能感兴趣的:(Java)