java通过模板实现word文档导出

我这是用easypoi导出docx文档
docx 模板 字段用 {{ }} 包含
easypoi 地址 ( http://doc.wupaas.com/docs/easypoi/easypoi-1c3a7tlsc85jn )
例:

/**
maven依赖
**/
    
        
            cn.afterturn
            easypoi-spring-boot-starter
            4.0.0
        
/**
业务层
**/
   @SneakyThrows
    @Override
    public void downloadWord(PerformanceSecurityVO entity, HttpServletResponse response) {
        String  fileName = "测试.docx";
        //实体转map
       Map result = JSON.parseObject(JSON.toJSONString(entity), Map.class);
 //        Map result = EasyPoiUtil.entityToMap(entity);
        EasyPoiUtil.downloadWord(fileName, result, response);
    }
import cn.afterturn.easypoi.word.WordExportUtil;
import com.ylxx.cloud.exception.ext.ServiceException;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.util.ResourceUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

public class EasyPoiUtil {

    public static void downloadWord(String fileName, Map params, HttpServletResponse response) {
        String path = getPath(fileName);//我这放 resources包下
        try {
            //获取模板文档
            
            File rootFile = new File(ResourceUtils.getURL("classpath:").getPath());
            File file= new File(rootFile, path);

            XWPFDocument word = WordExportUtil.exportWord07(file.getPath(), params);
            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
            OutputStream out = response.getOutputStream();
            word.write(out);
            out.flush();
            out.close();
        } catch (Exception e) {
            throw new ServiceException("导出失败,请联系网站管理员!", e);
        }
    }

   
    public static String getPath(String filename) {
        filename = "/word/" + filename;
        return filename;
    }

  
    /**
     实体类转Map
     */
    public static Map entityToMap(Object object) {
        Map map = new HashMap<>();
        for (Field field : object.getClass().getDeclaredFields()) {
            try {
                boolean flag = field.isAccessible();
                field.setAccessible(true);
                Object o = field.get(object);
                map.put(field.getName(), o);
                field.setAccessible(flag);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return map;
    }
}

你可能感兴趣的:(java通过模板实现word文档导出)