Newer
Older
newfiber-termite / newfiber-common / newfiber-common-office / src / main / java / com / newfiber / utils / WordBaseService.java
package com.newfiber.utils;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.xwpf.usermodel.*;

import java.io.*;
import java.util.Map;

/**
 * word导出实现
 * <p>
 * date: 2023/3/23 下午 07:10
 *
 * @author: LuFan
 * @since JDK 1.8
 */
public class WordBaseService {

    private static Log log = LogFactory.getLog(WordUtil.class);


    public byte[] toWordList(Object wordData, String templateBasePath) throws Exception {
        InputStream templateInputStream = this.getClass().getResourceAsStream(templateBasePath);
        byte[] bytes = null;
        if (wordData != null) {
            bytes = toWordAllModelAnalysisPublic(WordUtil.setMapObject(wordData), templateInputStream);
        }
        return bytes;
    }

    private static byte[] toWordAllModelAnalysisPublic(Map<String, Object> wordData, InputStream templateInputStream) throws Exception {
        byte[] bytes = null;
        if (wordData != null) {
            try {
                // 替换业务数据到模板对应位置,返回文档对象
                XWPFDocument doc = WordUtil.generateWord(wordData, templateInputStream);
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                doc.write(byteArrayOutputStream);
                bytes = byteArrayOutputStream.toByteArray();
                byteArrayOutputStream.close();
            } catch (Exception e) {
                log.error("文件处理异常", e);
            }
        }
        return bytes;
    }
}