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中

    @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) {
    //1、入库调用接口
    } 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');

      

Springboot使用EasyExcel(仅限自己收藏)的更多相关文章

  1. HTC仅限拨打紧急电话

    问题描述: 我手上有台 HTC One V 没碰没撞,突然打不出电话,信号上显示一个叉,屏幕上显示“仅限拨打紧急电话” 解决办法:经百度,原来很多HTC机子都有这种情况,幸好不是硬件坏了,只需按以下步 ...

  2. 真正的手机破解wifi密码,aircrack-ng,reaver,仅限mx2(BCM4330芯片)

    仅限mx2(BCM4330芯片),mx可能有戏没测试(BCM4329?),mx3不行. PS:原生安卓应用,非虚拟机 reaver,不知道是啥的看这里http://tieba.baidu.com/p/ ...

  3. bayaim_mysql_忘记密码 [仅限 5.6以下]

    bayaim_mysql_忘记密码 [仅限 5.6以下] 原创 作者:bayaim 时间:2017-12-26 10:47:41 8 0删除编辑 忘记root密码------------------- ...

  4. SpringBoot基于easyexcel导出和写入Excel

      easyexcel是阿里巴巴旗下开源项目,主要用于Excel文件的导入和导出处理,今天我们利用SpringBoot和easyexcel实战演示如何导出和写入Excel文件. 一.加入我们需要的ea ...

  5. SpringBoot图文教程14—SpringBoot集成EasyExcel「上」

    有天上飞的概念,就要有落地的实现 概念十遍不如代码一遍,朋友,希望你把文中所有的代码案例都敲一遍 先赞后看,养成习惯 SpringBoot 图文教程系列文章目录 SpringBoot图文教程1「概念+ ...

  6. 粉丝福利:收藏已久的Java架构资料免费送(仅限3天)

    有段时间没跟各位粉丝分享编程资源福利了,看了下自己的百度网盘,就剩下这个我认为是比较好的Java架构师学习资料了,相信这套资料可以对你进阶高级工程师有帮助. Java架构师技术进阶路线图 架构技术进阶 ...

  7. springboot jar 部署到linux之后 获取类资源文件问题-- 仅限linux 下 情况比较特殊 需要获取打到jar内的 讲台资源 只能通过流获取,根据路径获取不到指定文件 nullpointExption

    https://blog.csdn.net/qq_27000425/article/details/72897282 ClassPathResource类,如果没有指定相对的类名,该类将从类的根路径开 ...

  8. springboot整合easyexcel实现Excel导入导出

    easyexcel:快速.简单避免OOM的java处理Excel工具 Java解析.生成Excel比较有名的框架有Apache poi.jxl.但他们都存在一个严重的问题就是非常的耗内存,poi有一套 ...

  9. 基于令牌桶算法实现的SpringBoot分布式无锁限流插件

    本文档不会是最新的,最新的请看Github! 1.简介 基于令牌桶算法和漏桶算法实现的纳秒级分布式无锁限流插件,完美嵌入SpringBoot.SpringCloud应用,支持接口限流.方法限流.系统限 ...

随机推荐

  1. 【应用服务 App Service】当遇见某些域名在Azure App Service中无法解析的错误,可以通过设置指定DNS解析服务器来解决

    问题情形 当访问部署在Azure App Service中的应用返回 "The remote name could not be resolved: ''xxxxxx.com'" ...

  2. flutter——android报错建议Suggestion: add 'tools:replace="android:label"'

    问题: 安装了一个新包,android出现了报错,建议add 'tools:replace="android:label"'. 原因: 项目application的label属性冲 ...

  3. Mybatis项目搭建

    MyBatis是一个优秀的持久层框架.原生的jdbc操作存在大量的重复性代码(如注册驱动,创建连接,创建statement,结果集检测等).框架的作用就是把这些繁琐的代码封装. MyBatis通过XM ...

  4. 使用Socket通信(二)

    这个socket有梗,主要是服务器端有梗,可能大家会碰到同样的问题,网上查了好久,这里分享一下解决办法.首先在第一个module建一个类SimpleServer,这个类就是服务端,建好之后在代码左边有 ...

  5. B. Two Arrays 解析(思維)

    Codeforce 1417 B. Two Arrays 解析(思維) 今天我們來看看CF1417B 題目連結 題目 略,請直接看原題. 前言 a @copyright petjelinux 版權所有 ...

  6. Rancher 2.5特性解读丨更简单友好的API和Dashboard

    本文来自Rancher Labs 关注我们,看K8S干货教程 作者简介 张智博,Rancher中国研发与产品总监.7年云计算领域经验,一直活跃在研发一线,经历了OpenStack到Kubernetes ...

  7. 1.DRF初始化

    1.DRF框架的8个核心功能   1.认证(用户登录校验用户名密码或者token是否合法) 2.权限(根据不同的用户角色,可以操作不同的表) 3.限流(限制接口访问速度) 4.序列化(返回json) ...

  8. rabbitmq(一)-基础入门

    原文地址:https://www.jianshu.com/p/e186a7fce8cc 在学东西之前,我们先有一个方法论,知道如何学习.学习一个东西一般都遵循以下几个环节: xxx是什么,诞生的原因, ...

  9. node转发请求 .csv格式文件下载 中文乱码问题 + 文件上传笔记

    用户无法直接访问后台接口 需要node端转发请求 并将数据以.csv文件格式生成以供客户端下载. 很不幸出现了中文乱码的问题 挖了各种坟帖,下了各种依赖包,csv.json2csv.bufferHel ...

  10. Grafana+Prometheus+node_exporter监控,Grafana无法显示数据的问题

    环境搭建: 被测linux机器上部署了Grafana,Prometheus,node_exporter,并成功启动了它们. Grafana中已经创建了Prometheus数据源,并测试通过,并且导入了 ...