easypoi 导出(动态列表)

@RequestMapping(value = "/output", method = RequestMethod.GET)
    public void outputExcel(HttpServletResponse response) throws IllegalAccessException {
        String fileName = "food-导出.xls";

        List<ExcelExportEntity> beanList = new ArrayList<ExcelExportEntity>();
        beanList.add(new ExcelExportEntity("类型", "type"));
        beanList.add(new ExcelExportEntity("名称", "name"));
//        beanList.add(new ExcelExportEntity("名称(英文)", "nameEN"));
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

        List<Food> foods = getFoods();
        for (Food item : foods) {
            list.add(objectToMap(item));
        }

        writeExcelToStream(fileName, beanList, list, response);
    }


/**
     * 写入excel到流
     *
     * @param response
     * @param fileName
     */
    private <T> void writeExcelToStream(String fileName, List<ExcelExportEntity> entity, List<T> dtoLst, HttpServletResponse response) {
        try {
            // easyPoi操作excel
            Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), entity, dtoLst);
            // 设置响应头
            response.setHeader("content-Type", "application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
            // 写入到流中
            ServletOutputStream outputStream = response.getOutputStream();
            workbook.write(outputStream);
            workbook.close();
            outputStream.close();
        } catch (Exception e) {
//            log.error(e.getMessage());
            try {
                response.setHeader("Content-type", "text/html;charset=UTF-8");
                response.setCharacterEncoding("UTF-8");
                PrintWriter pw = response.getWriter();
                pw.write("导出文件异常!");
            } catch (Exception e1) {
//                log.error(e1.getMessage());
            }
        }
    }

    public static Map<String, Object> objectToMap(Object obj) throws IllegalAccessException {
        Map<String, Object> map = new HashMap<>();
        Class<?> clazz = obj.getClass();
        System.out.println(clazz);
        for (Field field : clazz.getDeclaredFields()) {
            field.setAccessible(true);
            String fieldName = field.getName();
            Object value = field.get(obj);
            map.put(fieldName, value);
        }
        return map;
    }

 

posted @ 2021-01-14 10:09  jamess  阅读(3319)  评论(0编辑  收藏  举报