easyexcel工具使用

easyexcel是阿里开源的关于excel处理的工具包,Github地址

在Github的md上已经讲解了一些基础的用法,这里主要是对基础使用进行简单的二次封装方便使用
/**
 * http封装
 */
public static void httpExportByOneSheet(HttpServletResponse response, List<? extends BaseRowModel> list,Class<? extends BaseRowModel> clazz,  String fileName) throws Exception {
        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes("gbk"), "iso8859-1"));
        response.setContentType("application/octet-stream");

        OutputStream out = response.getOutputStream();
        ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX, true);

        Sheet sheet1 = new Sheet(1, getHeadLineNum(clazz), clazz, fileName, null);
        writer.write(list, sheet1);
        writer.finish();
        out.flush();
    }
/**
 * 本地导出封装
 */
public static String localExport(List<? extends BaseRowModel> list, Class<? extends BaseRowModel> clazz, String exportPath) throws Exception {
        FileUtil.checkAndCreateDirs(exportPath);
        if(!exportPath.endsWith(File.separator)){
            exportPath += File.separator;
        }
        String fileName = getFileName();
        String filePath = FileUtil.checkAndCreateFile(exportPath + fileName + ".xlsx");
        OutputStream out = new FileOutputStream(filePath);
        ExcelWriter writer = EasyExcelFactory.getWriter(out);


        Sheet sheet = new Sheet(1, getHeadLineNum(clazz), clazz, fileName, null);
        writer.write(list, sheet);
        writer.finish();
        out.close();
        return exportPath + fileName + ".xlsx";
    }
    private static int getHeadLineNum(Class<? extends BaseRowModel> clazz) {
        int headLineNum = 0;
        for (Field declaredField : clazz.getDeclaredFields()) {
            ExcelProperty annotation = declaredField.getAnnotation(ExcelProperty.class);
            if (annotation != null && annotation.value().length > headLineNum) {
                headLineNum = annotation.value().length;
            }
        }
        return headLineNum;
    }

    private static String getFileName() {
        StringBuilder sb = new StringBuilder(System.currentTimeMillis() + "_");
        Random random = new Random();
        for (int i=0; i<4; i++) {
            sb.append(random.nextInt(9));
        }
        return sb.toString();
    }

可以在此上增加其他处理,如excel样式或者多sheet等,此demo仅起抛砖引玉的作用。

你可能感兴趣的:(java)