zoukankan      html  css  js  c++  java
  • springBoot excel导出 下载 超简单

    1.导入maven依赖包

    <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>easyexcel</artifactId>
                <version>1.1.1</version>
            </dependency>

    新建以下工具类

    package com.mybatis.plus.excel;
    
    import com.alibaba.excel.ExcelReader;
    import com.alibaba.excel.ExcelWriter;
    import com.alibaba.excel.metadata.BaseRowModel;
    import com.alibaba.excel.metadata.Sheet;
    import com.alibaba.excel.support.ExcelTypeEnum;
    import org.springframework.web.multipart.MultipartFile;
    
    import javax.servlet.http.HttpServletResponse;
    import java.io.BufferedInputStream;
    import java.io.File;
    import java.io.IOException;
    import java.io.OutputStream;
    import java.util.List;
    
    /**
     * @Author pt
     * @Description 工具类
     * @Date 2018-06-06
     * @Time 14:07
     */
    public class ExcelUtil {
        /**
         * 读取 Excel(多个 sheet)
         *
         * @param excel    文件
         * @param rowModel 实体类映射,继承 BaseRowModel 类
         * @return Excel 数据 list
         */
        public static List<Object> readExcel(MultipartFile excel, BaseRowModel rowModel) {
            ExcelListener excelListener = new ExcelListener();
            ExcelReader reader = getReader(excel, excelListener);
            if (reader == null) {
                return null;
            }
            for (Sheet sheet : reader.getSheets()) {
                if (rowModel != null) {
                    sheet.setClazz(rowModel.getClass());
                }
                reader.read(sheet);
            }
            return excelListener.getDatas();
        }
    
        /**
         * 读取某个 sheet 的 Excel
         *
         * @param excel    文件
         * @param rowModel 实体类映射,继承 BaseRowModel 类
         * @param sheetNo  sheet 的序号 从1开始
         * @return Excel 数据 list
         */
        public static List<Object> readExcel(MultipartFile excel, BaseRowModel rowModel, int sheetNo) {
            return readExcel(excel, rowModel, sheetNo, 1);
        }
    
        /**
         * 读取某个 sheet 的 Excel
         *
         * @param excel       文件
         * @param rowModel    实体类映射,继承 BaseRowModel 类
         * @param sheetNo     sheet 的序号 从1开始
         * @param headLineNum 表头行数,默认为1
         * @return Excel 数据 list
         */
        public static List<Object> readExcel(MultipartFile excel, BaseRowModel rowModel, int sheetNo,
                                             int headLineNum) {
            ExcelListener excelListener = new ExcelListener();
            ExcelReader reader = getReader(excel, excelListener);
            if (reader == null) {
                return null;
            }
            reader.read(new Sheet(sheetNo, headLineNum, rowModel.getClass()));
            return excelListener.getDatas();
        }
    
        /**
         * 导出 Excel :一个 sheet,带表头
         *
         * @param response  HttpServletResponse
         * @param list      数据 list,每个元素为一个 BaseRowModel
         * @param fileName  导出的文件名
         * @param sheetName 导入文件的 sheet 名
         * @param object    映射实体类,Excel 模型
         */
        public static void writeExcel(HttpServletResponse response, List<? extends BaseRowModel> list,
                                      String fileName, String sheetName, BaseRowModel object) {
            ExcelWriter writer = new ExcelWriter(getOutputStream(fileName, response), ExcelTypeEnum.XLSX);
            Sheet sheet = new Sheet(1, 0, object.getClass());
            sheet.setSheetName(sheetName);
            writer.write(list, sheet);
            writer.finish();
        }
    
        /**
         * 导出 Excel :多个 sheet,带表头
         *
         * @param response  HttpServletResponse
         * @param list      数据 list,每个元素为一个 BaseRowModel
         * @param fileName  导出的文件名
         * @param sheetName 导入文件的 sheet 名
         * @param object    映射实体类,Excel 模型
         */
        public static ExcelWriterFactroy writeExcelWithSheets(HttpServletResponse response, List<? extends BaseRowModel> list,
                                                              String fileName, String sheetName, BaseRowModel object) {
            ExcelWriterFactroy writer = new ExcelWriterFactroy(getOutputStream(fileName, response), ExcelTypeEnum.XLSX);
            Sheet sheet = new Sheet(1, 0, object.getClass());
            sheet.setSheetName(sheetName);
            writer.write(list, sheet);
            return writer;
        }
    
        /**
         * 导出文件时为Writer生成OutputStream
         */
        private static OutputStream getOutputStream(String fileName, HttpServletResponse response) {
            //创建本地文件
            String filePath = fileName + ".xlsx";
            File dbfFile = new File(filePath);
            try {
                if (!dbfFile.exists() || dbfFile.isDirectory()) {
                    dbfFile.createNewFile();
                }
                fileName = new String(filePath.getBytes(), "ISO-8859-1");
                response.addHeader("Content-Disposition", "filename=" + fileName);
                return response.getOutputStream();
            } catch (IOException e) {
                throw new ExcelException("创建文件失败!");
            }
        }
    
        /**
         * 返回 ExcelReader
         *
         * @param excel         需要解析的 Excel 文件
         * @param excelListener new ExcelListener()
         */
        private static ExcelReader getReader(MultipartFile excel,
                                             ExcelListener excelListener) {
            String filename = excel.getOriginalFilename();
            if (filename == null || (!filename.toLowerCase().endsWith(".xls") && !filename.toLowerCase().endsWith(".xlsx"))) {
                throw new ExcelException("文件格式错误!");
            }
            try {
                BufferedInputStream bufferedInputStream = new BufferedInputStream(excel.getInputStream());
                return new ExcelReader(bufferedInputStream, null, excelListener, false);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
    }
    package com.mybatis.plus.excel;
    
    /**
     *
     *
     * @Author pt
     * @Description Excel 解析 Exception
     * @Date 2018-06-06
     * @Time 15:56
     */
    public class ExcelException extends RuntimeException {
        public ExcelException(String message) {
            super(message);
        }
    }
    package com.mybatis.plus.excel;
    
    
    import com.alibaba.excel.context.AnalysisContext;
    import com.alibaba.excel.event.AnalysisEventListener;
    
    import java.util.ArrayList;
    import java.util.List;
    
    /**
     * @Author pt
     * @Description 监听类,可以自定义
     * @Date 2018-06-05
     * @Time 16:58
     */
    public class ExcelListener extends AnalysisEventListener {
    
        //自定义用于暂时存储data。
        //可以通过实例获取该值
        private List<Object> datas = new ArrayList<>();
    
        /**
         * 通过 AnalysisContext 对象还可以获取当前 sheet,当前行等数据
         */
        @Override
        public void invoke(Object object, AnalysisContext context) {
            //数据存储到list,供批量处理,或后续自己业务逻辑处理。
            datas.add(object);
            //根据业务自行 do something
            doSomething();
    
            /*
            如数据过大,可以进行定量分批处理
            if(datas.size()<=100){
                datas.add(object);
            }else {
                doSomething();
                datas = new ArrayList<Object>();
            }
             */
    
        }
    
        /**
         * 根据业务自行实现该方法
         */
        private void doSomething() {
        }
    
        @Override
        public void doAfterAllAnalysed(AnalysisContext context) {
            /*
                datas.clear();
                解析结束销毁不用的资源
             */
        }
    
        public List<Object> getDatas() {
            return datas;
        }
    
        public void setDatas(List<Object> datas) {
            this.datas = datas;
        }
    }
    package com.mybatis.plus.excel;
    
    import com.alibaba.excel.ExcelWriter;
    import com.alibaba.excel.metadata.BaseRowModel;
    import com.alibaba.excel.metadata.Sheet;
    import com.alibaba.excel.support.ExcelTypeEnum;
    
    import java.io.IOException;
    import java.io.OutputStream;
    import java.util.List;
    
    /**
     * Created with IntelliJ IDEA
     *
     * @Author pt
     * @Description
     * @Date 2018-06-07
     * @Time 16:47
     */
    public class ExcelWriterFactroy extends ExcelWriter {
        private OutputStream outputStream;
        private int sheetNo = 1;
    
        public ExcelWriterFactroy(OutputStream outputStream, ExcelTypeEnum typeEnum) {
            super(outputStream, typeEnum);
            this.outputStream = outputStream;
        }
    
        public ExcelWriterFactroy write(List<? extends BaseRowModel> list, String sheetName,
                                        BaseRowModel object) {
            this.sheetNo++;
            try {
                Sheet sheet = new Sheet(sheetNo, 0, object.getClass());
                sheet.setSheetName(sheetName);
                this.write(list, sheet);
            } catch (Exception ex) {
                ex.printStackTrace();
                try {
                    outputStream.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return this;
        }
    
        @Override
        public void finish() {
            super.finish();
            try {
                outputStream.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    创建导出表格对应实体

    package com.mybatis.plus.dto;
    
    import com.alibaba.excel.annotation.ExcelProperty;
    import com.alibaba.excel.metadata.BaseRowModel;
    import lombok.Data;
    
    @Data
    public class ExcelTestDto extends BaseRowModel {
    
        @ExcelProperty(value = "字典描述")
        private String dictDesc;
    
        @ExcelProperty(value = "字典名称")
        private String dictName;
    }

    业务逻辑代码

    @RequestMapping("export")
        public String export(HttpServletResponse response){
            List<Dict> list = iDictService.list();
            List<ExcelTestDto> excelDtos = new ArrayList<>();
            for (Dict dict : list) {
                ExcelTestDto excelDto = new ExcelTestDto();
                BeanUtil.copyProperties(dict,excelDto);
                excelDtos.add(excelDto);
            }
            String key = DateUtil.format(new Date(), "yyyy-MM-dd-HH-mm-ss");
            // 配置文件下载
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream");
            ExcelUtil.writeExcel(response, excelDtos, key, "sheet1", new ExcelTestDto());
            return "success";
        }

    最后在浏览器url输入导出接口地址 导出效果

  • 相关阅读:
    svn版本控制器在vs2013中的使用
    在本地环境用虚拟机win2008 sever搭建VS2013 + SVN 代码版本控制环境
    luogu 2422 良好的感觉
    loj 10181 绿色通道
    luogu 2569 [SCOI2010]股票交易
    luogu 3946 ことりのおやつ(小鸟的点心)
    luogu 2865 [USACO06NOV]路障Roadblocks
    luogu 4554 小明的游戏
    luogu 2411 白银莲花池 && luogu 1606 Lilypad Pond
    luogu 2850 [USACO06DEC]虫洞Wormholes
  • 原文地址:https://www.cnblogs.com/guanxiaohe/p/13322363.html
Copyright © 2011-2022 走看看