1. 程式人生 > >使用EasyPoi根據模板匯出Excel或word文件

使用EasyPoi根據模板匯出Excel或word文件

接著上篇文章 Java根據模板匯出Excel並生成多個Sheet 簡單介紹下EasyPoi的使用,直接上程式碼吧

首先當然是先引入jar包了,看下圖

其次,還是貼程式碼吧看例項,下面是根據模板匯出的工具類,包含Excel和word

/**
 * 匯出Excel或Word檔案
 * @ClassName:ExportExcelOrWord
 * @author leon
 * @createDate 2018年11月26日 下午14:25:27
 * @version v1.0
 * @classRemarks TODO
 */
@Configuration
public class ExportExcelOrWord {
    
    private static Logger logger = LoggerFactory.getLogger(ExportExcelOrWord.class);
    
    //模板地址
    @Value("${fileTemplateUrl}")
    private String fileTemplateUrl="D:/";
    //檔案儲存地址
    @Value("${fileGoalUrl}")
    private String fileGoalUrl="D:/export/";
    
    /**
     *  匯出word資料(07版)
     * @param params map資料集合
     * @param fileName 模板名稱
     * @param goalName 檔名稱
     * @return 檔案儲存地址
     * @throws Exception
     */
    public String exportWord(Map<String, Object> params, String fileName, String goalName){
        
        try {
            fileName=fileTemplateUrl+fileName+".docx";
            XWPFDocument doc = WordExportUtil.exportWord07(fileName, params);
            // 判斷檔案存放地址是否存在,沒有則建立
            File savefile = new File(fileGoalUrl);
            if (!savefile.exists()) {
                logger.info("匯出word資料時儲存檔案目錄不存在,為您建立資料夾!");
                savefile.mkdirs();
            }
            goalName=fileGoalUrl+goalName+".docx";
            FileOutputStream fos = new FileOutputStream(goalName);
            doc.write(fos);
            fos.close();
        }  catch (Exception e) {
            e.printStackTrace();
            logger.error("匯出word資料異常:"+e);
            return null;
        }
        return goalName;
    }
    
   

    /**
     * 按模板匯出Excel資料
     * @param params 資料
     * @param fileName 模板名稱
     * @param goalName 檔名稱
     * @return 檔案儲存地址
     * @throws Exception
     */
    public String exportExcel(Map<String, Object> params, String fileName, String goalName){
        
        try {
            fileName=fileTemplateUrl+fileName+".xlsx";
            TemplateExportParams templateUrl = new TemplateExportParams(fileName);
            Workbook workbook = ExcelExportUtil.exportExcel(templateUrl, params);
            // 判斷檔案存放地址是否存在,沒有則建立
            File savefile = new File(fileGoalUrl);
            if (!savefile.exists()) {
                logger.info("按模板匯出Excel資料時儲存檔案目錄不存在,為您建立資料夾!");
                savefile.mkdirs();
            }
            goalName=fileGoalUrl+goalName+".xlsx";
            FileOutputStream fos = new FileOutputStream(goalName);
            workbook.write(fos);
            fos.close();
        }catch (IOException e) {
            e.printStackTrace();
            logger.error("按模板匯出Excel資料異常:"+e);
            return null;
        }
        return goalName;
    }
    
    /**
     * 按模板匯出Excel資料(支援檔案流讀取檔案)
     * @param params 資料
     * @param fileName 模板名稱
     * @param goalName 檔名稱
     * @return 檔案儲存地址
     * @throws Exception
     */
    public String exportExcel(Map<String, Object> params, String fileName, String goalName,HttpServletResponse response){
        
        try {
            fileName=fileTemplateUrl+fileName+".xlsx";
            TemplateExportParams templateUrl = new TemplateExportParams(fileName);
            Workbook workbook = ExcelExportUtil.exportExcel(templateUrl, params);
            // 判斷檔案存放地址是否存在,沒有則建立
            File savefile = new File(fileGoalUrl);
            if (!savefile.exists()) {
                logger.info("按模板匯出Excel資料時儲存檔案目錄不存在,為您建立資料夾!");
                savefile.mkdirs();
            }
            //寫檔案流
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(goalName+".xlsx", "UTF-8"));
            workbook.write(response.getOutputStream());
            //寫檔案
            goalName=fileGoalUrl+goalName+".xlsx";
            FileOutputStream fos = new FileOutputStream(goalName);
            workbook.write(fos);
            fos.close();
        }catch (IOException e) {
            e.printStackTrace();
            logger.error("按模板匯出Excel資料異常:"+e);
            return null;
        }
        return goalName;
    }

    /**
     * 多sheet匯出Excel資料 每個sheet對應一個map,
     * key是sheet的NUM
     * @param params 資料集合
     * @param fileName 模板名稱
     * @param goalName 檔名稱
     * @return 檔案儲存地址
     * @throws Exception
     */
    public String exportExcelManeySheet(Map<Integer, Map<String, Object>> params, String fileName, String goalName){
        
        try {
            fileName=fileTemplateUrl+fileName+".xlsx";
            TemplateExportParams templateUrl = new TemplateExportParams(fileName);
            Workbook workbook = ExcelExportUtil.exportExcel(params, templateUrl);
            // 判斷檔案存放地址是否存在,沒有則建立
            File savefile = new File(fileGoalUrl);
            if (!savefile.exists()) {
                logger.info("多sheet匯出Excel資料的儲存檔案目錄不存在,為您建立資料夾!");
                savefile.mkdirs();
            }
            goalName=fileGoalUrl+goalName+".xlsx";
            FileOutputStream fos = new FileOutputStream(goalName);
            workbook.write(fos);
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("多sheet匯出Excel資料異常:"+e);
            return null;
        }
        return goalName;
    }
    
    /**
     * 單Excel檔案多sheet匯出Excel資料(注意sheetMap的key需與物件陣列中的物件名稱一致)
     * @param sheetMap map資料 如:sheetMap.put("PersonnelInfo",List<PersonnelInfo>);
     * @param sheetName sheet名稱陣列 如:new String[] {"人員資訊","家庭資訊",...};
     * @param objectClass 物件名稱陣列 如:new String[] {"PersonnelInfo","EducatInfo",...};
     * @param goalName 檔名稱
     * @return 檔案儲存地址
     * @throws Exception
     */
    public String exportExcelManeySheet(Map<Object, Object> sheetMap,String[] sheetName,String[] objectClass,String goalName){
        
        //判斷引數是否為空
        if (sheetName.length<1||objectClass.length<1||sheetMap==null||StringUtil.isNull(goalName)) {
            return null;
        }
        try {
            List<Map<String, Object>> sheetsList = new ArrayList<Map<String, Object>>() ;
            for (int i = 0; i < sheetName.length; i++) {
                //判斷map和物件是否為空
                if (StringUtil.isNull(objectClass[i]) &&sheetMap.get(objectClass[i]) == null) {
                    continue;
                }
                  ExportParams exportParams = new ExportParams() ;
                  exportParams.setSheetName(sheetName[i]);
                  exportParams.setStyle(ExcelExportStyler.class);
                Map<String, Object> exportMap = new HashMap<String, Object>();
                exportMap.put("title",exportParams);
                exportMap.put("entity",Class.forName("com.isoftstone.common.utils.excelUtil.entity."+objectClass[i]));
                exportMap.put("data", sheetMap.get(objectClass[i]));
                sheetsList.add(exportMap);
            }
            Workbook workbook = ExcelExportUtil.exportExcel(sheetsList, ExcelType.HSSF) ; 
            // 判斷檔案存放地址是否存在,沒有則建立
            File savefile = new File(fileGoalUrl);
            if (!savefile.exists()) {
                logger.info("單Excel檔案多sheet匯出Excel資料的儲存檔案目錄不存在,為您建立資料夾!");
                savefile.mkdirs();
            }
            goalName=fileGoalUrl+goalName+".xls";
            FileOutputStream fos = new FileOutputStream(goalName);
            workbook.write(fos);
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("單Excel檔案多sheet匯出Excel資料異常:"+e);
            return null;
        }
        return goalName;
    }
    
    /**
     * 一個excel 建立多個sheet
     * list 多個Map key title 對應表格
     * Title key entity 對應表格對應實體 
     * key data Collection 資料
     * @param list 資料集合
     * @param goalName 檔名稱
     * @return
     */
    public String exportExcel(List<Map<String, Object>> list, String goalName,HttpServletResponse response){
        
        try {
            Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);
            // 判斷檔案存放地址是否存在,沒有則建立
            File savefile = new File(fileGoalUrl);
            if (!savefile.exists()) {
                logger.info("按模板匯出Excel資料時儲存檔案目錄不存在,為您建立資料夾!");
                savefile.mkdirs();
            }
            //寫檔案流
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(goalName+".xls", "UTF-8"));
            workbook.write(response.getOutputStream());
            //寫檔案
            goalName=fileGoalUrl+goalName+".xls";
            FileOutputStream fos = new FileOutputStream(goalName);
            workbook.write(fos);
            fos.close();
        }catch (IOException e) {
            e.printStackTrace();
            logger.error("按模板匯出Excel資料異常:"+e);
            return null;
        }
        return goalName;
    }

下面看下呼叫過程,超簡單

public static void main(String[] args) throws Exception {
        
        ExportExcelOrWord ex=new ExportExcelOrWord();
        
        /*//離場證明
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("name", "leon");
        map.put("idNo", "436215688256556655");
        map.put("adY", "2018");
        map.put("adM", "11");
        map.put("adD", "30");
        map.put("leY", "2019");
        map.put("leM", "11");
        map.put("leD", "31");
        map.put("serDept", "華南事業部");
        map.put("serDate", "2018年 11月 28日— 2018年 11月 29日");
        String url=ex.exportWord(map, "離場證明", "離場證明模板資料");
        System.out.println("檔案地址:"+url);*/
        
        /*//工資清單(北京人車)/工資清單(其他)
        Map<String, Object> map = new HashMap<String, Object>();
        List<Map<String, Object>> listMap=new ArrayList<Map<String, Object>>();
        for (int i = 0; i < 2; i++) {
            Map<String, Object> mapIn = new HashMap<String, Object>();
            mapIn.put("city", "深圳"+i);
            mapIn.put("id", ""+i+1);
            mapIn.put("userNo", "A007");
            mapIn.put("surname", "Leon");
            mapIn.put("email", "[email protected]");
            listMap.add(mapIn);
        }
        map.put("maplist", listMap);//注意此處的maplist需要與檔案模板中fe後面的maplist名稱一致
        String url=ex.exportExcel(map, "工資清單(其他)", "工資清單(其它)模板資料");
        System.out.println("檔案地址:"+url);*/
        
        */
        //人員資訊彙總
        Map<Object, Object> sheetMap=new  HashMap<Object, Object>();
        List<RelatInfo> relatInfolist =new ArrayList<RelatInfo>();
        for (int i = 0; i < 2; i++) {
            RelatInfo relat=new RelatInfo();
            relat.setUserNo("B002"+i);
            relat.setSurname("Leon");
            relat.setTelephone("1387561245"+i);
            relatInfolist.add(relat);
        }
        List<WorkHistory> workHistorylist =new ArrayList<WorkHistory>();
        for (int i = 0; i < 3; i++) {
            WorkHistory work =new WorkHistory();
            work.setUserNo("A001"+i);
            work.setSurname("測試資料"+i);
            work.setBeginDate("2018/11/28");
            work.setEndDate("2018/11/28");
            work.setPosition("老闆");
            work.setCorporateName("吹水無敵");
            workHistorylist.add(work);
        }
        sheetMap.put("RelatInfo", relatInfolist);
        sheetMap.put("WorkHistory", workHistorylist);
        String url=ex.exportExcelManeySheet(sheetMap,new String[]{"工作經歷","家庭資訊"},new String[]{"RelatInfo","WorkHistory"},"D:/入場人員資訊彙總-測試.xls");
        System.out.println("檔案地址:"+url);
    }

說明一下,後面一個方法是多sheet匯出的方式,多sheet匯出easypoi的方法存在大坑,單條資料可以匯出多條不行需要重新實現,過於複雜這裡使用一個簡單的用實體類直接匯出多sheet,更多詳細的方法請參考原始碼,其實比較呼叫都比較簡單拼接引數容易遇坑,各位請注意

哦,對了,帶圖片的需要注意一下,需要設定引數(這裡簡單設定幾個屬性,其它請自行根據需求設定)

 還有個就是多sheet匯出時的樣式自定義的問題(個人這裡只設置了頭部樣式),上面其實有用到就下面圖中標註的

下面給出這個樣式類,大家可以自行擴充套件