admin 管理员组

文章数量: 887007

注意:这是简单实现,主要是对table,段落的实现,图片的拷贝,sdt的拷贝会在之后的文档中实现


<dependency>
    <groupId>com.deepoove</groupId>
    <artifactId>poi-tl</artifactId>
    <version>1.12.1</version>
</dependency>
import org.apachemons.collections4.CollectionUtils;
import org.apachemons.lang3.StringUtils;
import org.apache.poi.xwpf.usermodel.*;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class WriteOutWord {
    
    private static String def_path = "自己路劲"+System.currentTimeMillis()+".docx";

    public static void writeElementOut(List<IBodyElement> bodyElements,String path) {

        XWPFDocument newDoc = generateNewXWPFDoc(bodyElements);
        if(StringUtils.isBlank(path)){
            path = def_path;
        }
        writeOutFile(newDoc,path);
    }
/**
 * 生成新的XWPFDocument对象
 * @param bodyElements
 * @return
 */
private static XWPFDocument generateNewXWPFDoc(List<IBodyElement> bodyElements) {

    XWPFDocument newDoc = new XWPFDocument();
    for (int i = 0; i < bodyElements.size(); i++) {
        IBodyElement bodyElement = bodyElements.get(i);
        elementFitAndSet(newDoc,bodyElement);
    }
    return newDoc;
}

/**
 * 匹配文本类型
 * @param newDoc
 * @param bodyElement
 */
private static void elementFitAndSet(XWPFDocument newDoc,IBodyElement bodyElement){
    if(bodyElement instanceof XWPFParagraph){
        copyParagraph(newDoc,bodyElement);
    }else if(bodyElement instanceof XWPFTable){
        setTable(newDoc,bodyElement);
    }else {
        throw new RuntimeException("其余文本类型,还需要扩展");
    }
}

/**
 * copy 段落组件
 * @param newDoc
 * @param bodyElement
 */
private static void copyParagraph(XWPFDocument newDoc,IBodyElement bodyElement){
    XWPFParagraph paragraph = (XWPFParagraph)bodyElement;
    int paragraphIndex = getParagraphIndex(newDoc);
    newDoc.createParagraph();
    newDoc.setParagraph(paragraph,paragraphIndex);
}

/**
 * 获取段落组件的index值
 * @param newDoc
 * @return
 */
private static int getParagraphIndex(XWPFDocument newDoc){
    List<XWPFParagraph> paragraphs = newDoc.getParagraphs();
    if(CollectionUtils.isEmpty(paragraphs)){
        return 0;
    }
    return paragraphs.size();
}

/**
 * copy 表格组件
 * @param newDoc
 * @param bodyElement
 */
private static void setTable(XWPFDocument newDoc,IBodyElement bodyElement){
    XWPFTable table = (XWPFTable)bodyElement;
    int tableIndex = getTableIndex(newDoc);
    newDoc.createTable();
    newDoc.setTable(tableIndex,table);
}

/**
 * 获取表格组件的index值
 * @param newDoc
 * @return
 */
private static int getTableIndex(XWPFDocument newDoc){
    List<XWPFTable> tables = newDoc.getTables();
    if(CollectionUtils.isEmpty(tables)){
        return 0;
    }
    return tables.size();
}

/**
 * docx 写出到本地
 * @param newDoc
 * @param path
 */
public static void writeOutFile(XWPFDocument newDoc,String path){
    try {
        FileOutputStream out = new FileOutputStream(path);
        newDoc.write(out);
    }catch (IOException e){

    }
}

}

本文标签: 部分内容 文件 poi Word