Springboot使用EasyExcel(僅限本身收藏)

  1. pom文件依賴
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>easyexcel</artifactId>
        <version>1.1.2-beta5</version>
    </dependency>

      

  2. ExporExcelController 文件中
    @RequestMapping("/exce")
    @Controller
    public class ExporExcelController {
        //植入Service
        @Resource(name = "idemoService")
        private DemoService demoService;
    
        /*
         *直接輸出數據到前臺
         */
        @RequestMapping("/export")
        public String ExporExcel(HttpServletResponse response) throws Exception { //throws IOException {
            ExcelWriter writer = null;
            OutputStream outputStream = response.getOutputStream();
            try {
                //添加響應頭信息
                response.setHeader("Content-disposition", "attachment; filename=" + "catagory.xls");
                response.setContentType("application/msexcel;charset=UTF-8");//設置類型
                response.setHeader("Pragma", "No-cache");//設置頭
                response.setHeader("Cache-Control", "no-cache");//設置頭
                response.setDateHeader("Expires", 0);//設置日期頭
    
                //實例化 ExcelWriter
                writer = new ExcelWriter(outputStream, ExcelTypeEnum.XLS, true);
    
                //實例化表單
                Sheet sheet = new Sheet(1, 0, Catagory.class);
                sheet.setSheetName("測試");
                //獲取數據
                List<Catagory> catagoryList = demoService.findAllToExcel();
                //System.out.println(catagoryList.size());
                //輸出
                writer.write(catagoryList, sheet);
                writer.finish();
                outputStream.flush();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    response.getOutputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }
    
        /*
         *
         */
        @RequestMapping("/import")
        @ResponseBody
        public void importExcel(@RequestParam("file") MultipartFile file) throws IOException {
           
                InputStream inputStream = file.getInputStream();
                //實例化實現了AnalysisEventListener接口的類
                ExcelListener listener = new ExcelListener();
                //傳入參數
                ExcelReader excelReader = new ExcelReader(inputStream, ExcelTypeEnum.XLS, null, listener);
                //讀取信息
                excelReader.read(new Sheet(1, 1, Catagory.class));
                //獲取數據
                List<Object> list = listener.getDatas();
                List<Catagory> catagoryList = new ArrayList<Catagory>();
                Catagory catagory = new Catagory();
    
                //轉換數據類型,並插入到數據庫
                for (int i = 0; i < list.size(); i++) {
                    catagory = (Catagory) list.get(i);
                      System.out.println(catagory);
                    demoService.addForExcel(catagory);
                }
            
    
        }
    /*
    *在服務器上生成excel
     */
        @RequestMapping("/exportserver")
        @ResponseBody
        public String writeBySimple() {
            /*
            System.out.println(System.getProperty("user.dir"));
            String path =System.getProperty("user.dir")+"\\Index"; //所建立文件目錄
            */
            String path = System.getProperty("user.dir")+"\\target\\classes\\static";
            String filePath = "tmpexcel";
            File f = new File(path+"\\"+filePath);
            if(!f.exists()) {
                f.mkdirs(); //建立目錄
            }
    
    
            String fileName = "測試.xlsx";
            List<List<Object>> data = new ArrayList<>();
            data.add(Arrays.asList("111", "222", "333"));
            data.add(Arrays.asList("111", "222", "333"));
            data.add(Arrays.asList("111", "222", "333"));
            List<String> head = Arrays.asList("表頭1", "表頭2", "表頭3");
            ExcelUtil.writeBySimple(path+"\\"+filePath+"\\"+fileName, data, head);
            return filePath+"\\"+fileName;
            //return null;
        }
    }

     

  3.  DeamDao中javascript

    @Component("DemoEmDAO")
    public interface DemoDAO {
        //excel查詢全部
        @Select("select id,name,sex,age from em")
        public List<Catagory> findAllToExcel() throws Exception;
        //添加
        public int addForExcel(Catagory model);
    }

      

  4. Model中
    @EqualsAndHashCode(callSuper = true)
    @Data
    public class Catagory extends BaseRowModel {
        @ExcelProperty(value = "id", index = 0)
        private Integer id;
    
        @ExcelProperty(value = "姓名", index = 1)
        private String name;
    
        @ExcelProperty(value = "性別", index = 2)
        private String sex;
    
        @ExcelProperty(value = "年齡", index = 3)
        private Integer age;
    
    }

      

  5. DemoService中
    public interface DemoService {
    
        //excel查詢全部
        public List<Catagory> findAllToExcel() throws Exception;
        //添加
        public int addForExcel(Catagory model);
    }

      

  6. DemoServiceImpl中
    @Service("idemoService")
    public class DemoServiceImpl implements DemoService {
        @Resource(name = "DemoEmDAO")
        private DemoDAO dao;
        @Override
        public List<Catagory> findAllToExcel() throws Exception {
           return dao.findAllToExcel();
        }
    
        @Override
        public int addForExcel(Catagory model) {
            dao.addForExcel(model);
            return 0;
        }
    }

      

  7. ExcelListener中
    public class ExcelListener extends AnalysisEventListener {
        //能夠經過實例獲取該值
        private List<Object> datas = new ArrayList<Object>();
    
        public void invoke(Object o, AnalysisContext analysisContext) {
            datas.add(o);//數據存儲到list,供批量處理,或後續本身業務邏輯處理。
            doSomething(o);//根據本身業務作處理
        }
    
        private void doSomething(Object object) {
            //一、入庫調用接口
        }
    
        public List<Object> getDatas() {
            return datas;
        }
        public void setDatas(List<Object> datas) {
            this.datas = datas;
        }
    
        public void doAfterAllAnalysed(AnalysisContext analysisContext) {
            // datas.clear();//解析結束銷燬不用的資源
        }
    }

      

  8. ExcleUtil中
    @Slf4j
    public class ExcelUtil {
      //  private static Logger logger = LoggerFactory.getLogger(ExcelUtil.class);
        private static Sheet initSheet;
    
        static {
            initSheet = new Sheet(1, 0);
            initSheet.setSheetName("sheet");
            //設置自適應寬度
            initSheet.setAutoWidth(Boolean.TRUE);
        }
    
        /**
         * 讀取少於1000行數據
         * @param filePath 文件絕對路徑
         * @return
         */
        public static List<Object> readLessThan1000Row(String filePath){
            return readLessThan1000RowBySheet(filePath,null);
        }
    
        /**
         * 讀小於1000行數據, 帶樣式
         * filePath 文件絕對路徑
         * initSheet :
         *      sheetNo: sheet頁碼,默認爲1
         *      headLineMun: 從第幾行開始讀取數據,默認爲0, 表示從第一行開始讀取
         *      clazz: 返回數據List<Object> 中Object的類名
         */
        public static List<Object> readLessThan1000RowBySheet(String filePath, Sheet sheet){
            if(!StringUtils.hasText(filePath)){
                return null;
            }
            Logger log = LoggerFactory.getLogger(ExcelUtil.class);
            sheet = sheet != null ? sheet : initSheet;
    
            InputStream fileStream = null;
            try {
                fileStream = new FileInputStream(filePath);
                return EasyExcelFactory.read(fileStream, sheet);
            } catch (FileNotFoundException e) {
                log.info("找不到文件或文件路徑錯誤, 文件:{}", filePath);
            }finally {
                try {
                    if(fileStream != null){
                        fileStream.close();
                    }
                } catch (IOException e) {
                    log.info("excel文件讀取失敗, 失敗緣由:{}", e);
    
                }
            }
            return null;
        }
    
        /**
         * 讀大於1000行數據
         * @param filePath 文件以爲路徑
         * @return
         */
        public static List<Object> readMoreThan1000Row(String filePath){
            return readMoreThan1000RowBySheet(filePath,null);
        }
    
        /**
         * 讀大於1000行數據, 帶樣式
         * @param filePath 文件以爲路徑
         * @return
         */
        public static List<Object> readMoreThan1000RowBySheet(String filePath, Sheet sheet){
            if(!StringUtils.hasText(filePath)){
                return null;
            }
            Logger log = LoggerFactory.getLogger(ExcelUtil.class);
            sheet = sheet != null ? sheet : initSheet;
    
            InputStream fileStream = null;
            try {
                fileStream = new FileInputStream(filePath);
                ExcelListener excelListener = new ExcelListener();
                EasyExcelFactory.readBySax(fileStream, sheet, excelListener);
                return excelListener.getDatas();
            } catch (FileNotFoundException e) {
                log.error("找不到文件或文件路徑錯誤, 文件:{}", filePath);
            }finally {
                try {
                    if(fileStream != null){
                        fileStream.close();
                    }
                } catch (IOException e) {
                    log.error("excel文件讀取失敗, 失敗緣由:{}", e);
                }
            }
            return null;
        }
    
        /**
         * 生成excle
         * @param filePath  絕對路徑, 如:/home/chenmingjian/Downloads/aaa.xlsx
         * @param data 數據源
         * @param head 表頭
         */
        public static void writeBySimple(String filePath, List<List<Object>> data, List<String> head){
            writeSimpleBySheet(filePath,data,head,null);
        }
    
        /**
         * 生成excle
         * @param filePath 絕對路徑, 如:/home/chenmingjian/Downloads/aaa.xlsx
         * @param data 數據源
         * @param sheet excle頁面樣式
         * @param head 表頭
         */
        public static void writeSimpleBySheet(String filePath, List<List<Object>> data, List<String> head, Sheet sheet){
            sheet = (sheet != null) ? sheet : initSheet;
    
            if(head != null){
                List<List<String>> list = new ArrayList<>();
                head.forEach(h -> list.add(Collections.singletonList(h)));
                sheet.setHead(list);
            }
    
            OutputStream outputStream = null;
            ExcelWriter writer = null;
            try {
                outputStream = new FileOutputStream(filePath);
                writer = EasyExcelFactory.getWriter(outputStream);
                writer.write1(data,sheet);
            } catch (FileNotFoundException e) {
               // log.error("找不到文件或文件路徑錯誤, 文件:{}", filePath);
                System.out.println("找不到文件或文件路徑錯誤, 文件:{}"+ filePath);
            }finally {
                try {
                    if(writer != null){
                        writer.finish();
                    }
    
                    if(outputStream != null){
                        outputStream.close();
                    }
    
                } catch (IOException e) {
                  //  log.error("excel文件導出失敗, 失敗緣由:{}", e);
                    System.out.println("excel文件導出失敗, 失敗緣由:{}");
                }
            }
    
        }
    
        /**
         * 生成excle
         * @param filePath 絕對路徑, 如:/home/chenmingjian/Downloads/aaa.xlsx
         * @param data 數據源
         */
        public static void writeWithTemplate(String filePath, List<? extends BaseRowModel> data){
            writeWithTemplateAndSheet(filePath,data,null);
        }
    
        /**
         * 生成excle
         * @param filePath 絕對路徑, 如:/home/chenmingjian/Downloads/aaa.xlsx
         * @param data 數據源
         * @param sheet excle頁面樣式
         */
        public static void writeWithTemplateAndSheet(String filePath, List<? extends BaseRowModel> data, Sheet sheet){
            if(CollectionUtils.isEmpty(data)){
                return;
            }
    
            sheet = (sheet != null) ? sheet : initSheet;
            sheet.setClazz(data.get(0).getClass());
    
            OutputStream outputStream = null;
            ExcelWriter writer = null;
            try {
                outputStream = new FileOutputStream(filePath);
                writer = EasyExcelFactory.getWriter(outputStream);
                writer.write(data,sheet);
            } catch (FileNotFoundException e) {
              //  log.error("找不到文件或文件路徑錯誤, 文件:{}", filePath);
                System.out.println("找不到文件或文件路徑錯誤, 文件:{}"+ filePath);
            }finally {
                try {
                    if(writer != null){
                        writer.finish();
                    }
    
                    if(outputStream != null){
                        outputStream.close();
                    }
                } catch (IOException e) {
                  //  log.error("excel文件導出失敗, 失敗緣由:{}", e);
                    System.out.println("excel文件導出失敗, 失敗緣由:{}");
                }
            }
    
        }
    
        /**
         * 生成多Sheet的excle
         * @param filePath 絕對路徑, 如:/home/chenmingjian/Downloads/aaa.xlsx
         * @param multipleSheelPropetys
         */
        public static void writeWithMultipleSheel(String filePath,List<MultipleSheelPropety> multipleSheelPropetys){
            if(CollectionUtils.isEmpty(multipleSheelPropetys)){
                return;
            }
    
            OutputStream outputStream = null;
            ExcelWriter writer = null;
            try {
                outputStream = new FileOutputStream(filePath);
                writer = EasyExcelFactory.getWriter(outputStream);
                for (MultipleSheelPropety multipleSheelPropety : multipleSheelPropetys) {
                    Sheet sheet = multipleSheelPropety.getSheet() != null ? multipleSheelPropety.getSheet() : initSheet;
                    if(!CollectionUtils.isEmpty(multipleSheelPropety.getData())){
                        sheet.setClazz(multipleSheelPropety.getData().get(0).getClass());
                    }
                    writer.write(multipleSheelPropety.getData(), sheet);
                }
    
            } catch (FileNotFoundException e) {
               // log.error("找不到文件或文件路徑錯誤, 文件:{}", filePath);
                System.out.println("找不到文件或文件路徑錯誤, 文件:{}"+ filePath);
            }finally {
                try {
                    if(writer != null){
                        writer.finish();
                    }
    
                    if(outputStream != null){
                        outputStream.close();
                    }
                } catch (IOException e) {
                   // log.error("excel文件導出失敗, 失敗緣由:{}", e);
                    System.out.println("excel文件導出失敗, 失敗緣由:{}");
                }
            }
    
        }
    
    }

      

  9. JsonDateSerializer中
    public class JsonDateSerializer extends JsonSerializer<Date> {
        private SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        @Override
        public void serialize(Date date, JsonGenerator gen, SerializerProvider provider)
                throws IOException, JsonProcessingException {
            String value = dateFormat.format(date);
            gen.writeString(value);
        }
    }

      

  10. MultipleSheelPropety中
    @Data
    public  class MultipleSheelPropety {
    
        private List<? extends BaseRowModel> data;
      //能夠經過實例獲取該值
       // private List<Object> data = new ArrayList<Object>();
        private Sheet sheet;
    
        public List<? extends BaseRowModel> getData() {
            return data;
        }
        public void setDatas(List<? extends BaseRowModel> data) {
            this.data = data;
        }
    
        public Sheet getSheet() {
            return sheet;
        }
    
        public void setSheet(Sheet sheet) {
            this.sheet = sheet;
        }
    }

      

  11. DemoMapper.xml中
    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
    <mapper namespace="com.exceldemo.demo.mapper.DemoDAO" >
        <resultMap id="BaseResultMap" type="com.exceldemo.demo.entity.Em" >
            <id column="id" property="id" jdbcType="INTEGER" />
            <result column="name" property="name" jdbcType="VARCHAR" />
            <result column="sex" property="sex" jdbcType="TIMESTAMP" />
            <result column="age" property="age" jdbcType="INTEGER" />
            <result column="createDate" property="createDate" jdbcType="TIMESTAMP" />
        </resultMap>
        <!--01.查詢全部記錄-->
        <select id="findAll" resultType="com.exceldemo.demo.entity.Em">
             select * from em
         </select>
        <!--excel導入-->
        <insert id="addForExcel">
            insert into em(name,sex,age,createDate) values(#{name},#{sex},#{age},now())
        </insert>
    </mapper>

      

  12. html文件
    <!DOCTYPE html>
    <html lang="zh-CN" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="utf-8" />
        <title>excel導入導出</title>
        <script type="text/javascript" th:src="@{/js/jquery-3.4.1.min.js}"></script>
    
    </head>
    <body>
    <!--表單提交-->
    <form action="/exce/import" method="post" enctype="multipart/form-data">
        <input type="file" name="file" id="file"/>
        <input type="submit" value="表單提交">
    
    </form>
    <!--經過js提交-->
    <input type="file" name="file" id="file2"/>
    <input name="btnSubmit" type="button" value="JS導入" onclick="fnImpotExcel()"/>
    <br>
    <input name="btnSubmit" type="button" value="導出excel1(直接輸出excel數據)" onclick="window.open('/exce/export')"/>
    <input name="btnSubmit" type="button" value="導出excel2(服務器上生成excel文件,返回文件地址)" onclick="fnExportExcel('/exce/exportserver')"/>
    </body>
    </html>
    <script>
        function fnImpotExcel(){
            var blob = document.getElementById('file2').files[0];
    
            var xhr = new XMLHttpRequest();
    
            xhr.onreadystatechange = function() {
                if(xhr.readyState == 4) {
                    if(xhr.responseText) {
                        alert(xhr.responseText);
                        // if(slices == 0) {
                        //  alert(2)
                        // }
                    }
    
                }
            };
    
    //構造form數據
            var fd = new FormData();
            fd.append("file", blob);
            fd.append("name", blob.name);
            xhr.open("POST", "/exce/import", false);
    
            //設置二進制文邊界件頭
            //xhr.setRequestHeader("X_Requested_With", location.href.split("/")[3].replace(/[^a-z]+/g, '$'));
            xhr.send(fd);
            /*
                $.ajax({
                    url: "/exce/import",
                    type: "post",
                    data: {field:document.getElementById('file2').files[0]},
                    success: function (data) {alert(data);
                        console.log(data);
                      //  data = decodeURIComponent(decodeURIComponent (data)).split(",");
                       // $.each(a,function (k,v) {
                         //   $("[data-id="+a[k]+"]").append(decodeURIComponent(decodeURIComponent (data[k])));
                       // })
                    }
                })
    
             */
        }
        //導出excel
        function fnExportExcel(url){
            $.ajax({
                url: url,
                type: "post",
                success: function (data) {
                    if(data!="") window.open("/"+data);
                }
            })
        }
    </script>

      

  13. SQL文件
    DROP TABLE IF EXISTS `em`;
    CREATE TABLE `em` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `name` varchar(255) DEFAULT NULL,
      `sex` varchar(10) DEFAULT NULL,
      `age` int(11) DEFAULT NULL,
      `createDate` datetime NOT NULL ON UPDATE CURRENT_TIMESTAMP,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;
    
    -- ----------------------------
    -- Records of em
    -- ----------------------------
    INSERT INTO `em` VALUES ('3', '張西', '女', '63', '2019-11-07 23:02:28');
    INSERT INTO `em` VALUES ('4', '蘭六', '男', '7', '2019-11-07 23:02:28');
    INSERT INTO `em` VALUES ('5', '蘭六11', '男', '11', '2019-11-07 23:05:28');
相關文章
相關標籤/搜索