springboot整合easypoi导出excel

easypoi导出excel文件

1、直接展示实现方法:controller层

    @GetMapping("/downloadByRoster")
    public R downLoadTemplateByRoster(Integer sccId, HttpServletResponse response,
                                                   HttpServletRequest request) throws Exception {// 获取模板
            String excelName = "xxxx年xx月制单模板xx批.xls";
            TemplateExportParams params = new TemplateExportParams("excel/xxxx年xx月制单模板xx批.xls");
            // 设置模板中的sheetName
            //    params.setSheetName("支付明细表");
            // 向模板中间设置
            HashMap<String, Object> map = new HashMap<String, Object>();

            List<Map<String, String>> listMap = new ArrayList<Map<String, String>>();
        //此处数据根据项目情况获得 List
<RosterVO> list = rosterDao.findRosterByMobiles(sccId); for (RosterVO roster : list) { HashMap<String, String> lm = new HashMap<String, String>(); lm.put("pdContractor", roster.getRsContractor()); lm.put("pdIdCard", roster.getRsIdCard()); lm.put("pdBankName", roster.getRsBankName()); lm.put("pdBankAccount", roster.getRsBankAccount()); lm.put("pdMobile", roster.getRsMobile()); listMap.add(lm); } map.put("maplist", listMap); // 获取excel Workbook workbook = ExcelExportUtil.exportExcel(params, map); ExcelUtil.exportExcel("excel", workbook, request, response);

2、excel导入导出工具类:此处只用看需要模板的根据map集合获取excel(workbook)导出

package io.renren.common.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;

/**
 * @program: ivvdata-security
 * @description: 文件导入导出工具
 * @author: HYJ
 * @create: 2019-09-25 14:16
 */
public class ExcelUtil {

    /**
     * 得到Workbook对象
     *
     * @param file
     * @return
     * @throws IOException
     */
    public static Workbook getWorkBook(MultipartFile file) throws IOException {
        // 这样写 excel 能兼容03和07
        InputStream is = file.getInputStream();
        Workbook hssfWorkbook = null;
        try {
            hssfWorkbook = new HSSFWorkbook(is);
        } catch (Exception ex) {
            is = file.getInputStream();
            hssfWorkbook = new XSSFWorkbook(is);
        }
        return hssfWorkbook;
    }


    /**
     * 需要模板的根据map集合获取excel(workbook)导出
     * @param fileName
     * @param workbook
     * @param request
     * @param response
     * @throws IOException
     */
    public static void exportExcel(String fileName, Workbook workbook, HttpServletRequest request, HttpServletResponse response)
            throws IOException {

        response.reset();
        response.setContentType("multipart/form-data");
        //解决下载时中文文件名乱码和下载时因为路径中包含中文文件名乱码,提示找不到文件
        String userAgent = request.getHeader("User-Agent");
        // 针对IE或者以IE为内核的浏览器:
        if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
            fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
        } else {
            // 非IE浏览器的处理:
            fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
        }

        // 判断excel文件类型,下载获取到的模板并重新命名
        if (workbook.getClass().getSimpleName().equals("HSSFWorkbook")) {
            response.setHeader("Content-Disposition",
                    "attachment; filename=" + new String(fileName.getBytes("UTF-8"), "iso8859-1") + ".xls");

        } else {
            response.setHeader("Content-Disposition",
                    "attachment; filename=" + new String(fileName.getBytes("UTF-8"), "iso8859-1") + ".xlsx");

        }

        // 输出流
        workbook.write(response.getOutputStream());
    }


    /**
     * 不需要模板导出excel的注解方式
     * @param exportParams
     * @param fileName
     * @param pojoClass
     * @param list
     * @param response
     * @throws IOException
     */
    public static void exportExcel(ExportParams exportParams, String fileName, Class<?> pojoClass, List<?> list,
                                   HttpServletResponse response) throws IOException {
        // 生成workbook并导出
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
        response.reset();     // 清空输出流
        response.setContentType("multipart/form-data");
        System.out.println(workbook.getClass().getSimpleName());
        // 下载excel并重新命名并判断是xlsx格式还是xls格式
        if (workbook.getClass().getSimpleName().equals("HSSFWorkbook")) {
            response.setHeader("Content-Disposition",
                    "attachment; filename=" + new String(fileName.getBytes("UTF-8"), "iso8859-1") + ".xls");
        } else {
            response.setHeader("Content-Disposition",
                    "attachment; filename=" + new String(fileName.getBytes("UTF-8"), "iso8859-1") + ".xlsx");
        }
        // 输出流
        workbook.write(response.getOutputStream());
    }


    /**
     * 不需要模板导出excel的注解方式,上传到服务器,返回的是下载路径
     * @param exportParams
     * @param fileName
     * @param pojoClass
     * @param list
     * @param response
     * @throws IOException
     */
    public static String exportExcel(ExportParams exportParams, String fileName, Class<?> pojoClass, List<?> list, 
                                   HttpServletResponse response, HttpServletRequest request) throws IOException {
   
        // 生成workbook并导出
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
        // 定义上传文件存放的路径
        String path1 = request.getSession().getServletContext().getRealPath("/temporaryUploadExcel/");
        // 定义文件在上传路径中的文件夹名称
        File folder = new File(path1);
        // 检测folder是否是文件夹,不是就创建
        if (!folder.isDirectory()) {
            folder.mkdirs();
        }
      

        // 下载excel并重新命名并判断是xlsx格式还是xls格式
        if (workbook.getClass().getSimpleName().equals("HSSFWorkbook")) {
            String excelName = fileName + ".xls";
            // 将workbook文件写入流并上传至服务器 path1:上传文件存放路径 excel:文件夹名称 excelName:文件名
            FileOutputStream fileOutputStream = new FileOutputStream(path1+ excelName);
            workbook.write(fileOutputStream);
            String path = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
                    + "/ivvdata-admin" + "/temporaryUploadExcel/" + excelName;
            return path;
        } else {
            String excelName = fileName + ".xls";
            // 将文件流写入文件并上传至服务器 path1:上传文件存放路径 excel:文件夹名称 excelName:文件名
            FileOutputStream fileOutputStream = new FileOutputStream(path1 + excelName);
            workbook.write(fileOutputStream);
            String path = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
                    + "/ivvdata-admin" + "/temporaryUploadExcel/"  + excelName;
            System.out.println("获取路径" + path);
            return path;
        }


    }


    /*
     *  下方所有方法根据自己情况选择加工使用,和上面加工过的方法存在一致
     */

    public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName,
                                   boolean isCreateHeader, HttpServletResponse response) {
        ExportParams exportParams = new ExportParams(title, sheetName);
        exportParams.setCreateHeadRows(isCreateHeader);
        defaultExport(list, pojoClass, fileName, response, exportParams);
    }

    public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName,
                                   HttpServletResponse response) {
        defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName));
    }

    public static void exportExcel(List<Map<String, Object>> list, String fileName, HttpServletResponse response) {
        defaultExport(list, fileName, response);
    }

    private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response,
                                      ExportParams exportParams) {
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
        if (workbook != null);
        downLoadExcel(fileName, response, workbook);
    }


    private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) {
        try {
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            // throw new NormalException(e.getMessage());
        }
    }

    private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) {
        Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);
        if (workbook != null);
        downLoadExcel(fileName, response, workbook);
    }

    public static <T> List<T> importExcel(String filePath, Integer titleRows, Integer headerRows, Class<T> pojoClass) {
        if (StringUtils.isBlank(filePath)) {
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        List<T> list = null;
        try {
            list = ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);
        } catch (NoSuchElementException e) {
            // throw new NormalException("模板不能为空");
        } catch (Exception e) {
            e.printStackTrace();
            // throw new NormalException(e.getMessage());
        }
        return list;
    }

    public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows,
                                          Class<T> pojoClass) {
        if (file == null) {
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        List<T> list = null;
        try {
            list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);
        } catch (NoSuchElementException e) {
            // throw new NormalException("excel文件不能为空");
        } catch (Exception e) {
            // throw new NormalException(e.getMessage());
            System.out.println(e.getMessage());
        }
        return list;
    }

}

3、模板来源:工程下resources文件夹下新建的excel文件夹中

 4、最重要的一点,模板到底该如何设置,参考http://easypoi.mydoc.io/中Excel模板版

猜你喜欢

转载自www.cnblogs.com/H-Dream/p/11815466.html