SpringBoot整合EasyPoi實現Excel的導入和導出(帶圖片)

2021-02-13 java1234

點擊上方藍色字體,選擇「標星公眾號」

優質文章,第一時間送達

66套java從入門到精通實戰課程分享

前言

實際工作中可能會用到Excel的導入和導出功能,Java操作Excel的方式有很多種,這裡簡單介紹一下如何使用EasyPoi來操作Excel。簡單的做個筆記,防止自己忘記。

EasyPoi文檔:http://easypoi.mydoc.io/

項目地址:https://gitee.com/lihongmin5211/springboot_easypoi

準備工作環境:

SpringBoot2.4.0、jdk8、Mysql5.7

表結構:

DROP TABLE IF EXISTS `student`;
CREATE TABLE `student`  (
  `id` int(11) NOT NULL COMMENT '主鍵,非遞增',
  `name` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '姓名',
  `photo` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '照片',
  `address` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '地址',
  `birthday` datetime(0) DEFAULT NULL COMMENT '出生日期',
  `tel` varchar(11) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '電話',
  `sex` varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '性別',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

Excel:

創建一個SpringBoot項目

過程這裡就不細說了

pom.xml文件:

        <!-- mybatis -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.4</version>
        </dependency>
        <!-- mysql -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!-- 連接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.9</version>
        </dependency>
        <!-- easypoi相關的jar包 -->
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-base</artifactId>
            <version>3.2.0</version>
        </dependency>
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-web</artifactId>
            <version>3.2.0</version>
        </dependency>
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-annotation</artifactId>
            <version>3.2.0</version>
        </dependency>
        <!-- freemarker -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>

application.yml:

server:
  port: 9001
spring:
  freemarker:
    suffix: .ftl
    cache: false
    charset: UTF-8
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=GMT%2B8
    username: root
    password: *****
  web:
    resources:
      static-locations: classpath:/static/
mybatis:
  mapper-locations: classpath:/mapper/*.xml
  type-aliases-package: com.lhm.entity
upload.dir: E:\java\study\springboot_easypoi\src\main\resources\static\imgs\

頁面準備:

templates目錄下新建一個studentList.ftl(這裡用的是layui)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>學生列表</title>
    <link rel="stylesheet" href="/layui/css/layui.css">
</head>
<body>
<style>
    //設置table的行高為自動適應
    .layui-table-cell {
        display: table-cell;
        vertical-align: middle;
    }
</style>
<div>
    <button type="button" class="layui-btn" id="upload"><i class="layui-icon"></i>導入Excel</button>
</div>
<div>
    <table class="layui-hide" id="studentTable"></table>
</div>
<div>
    <button type="button" class="layui-btn layui-btn-warm" onclick="exportExcel()">導出Excel</button>
</div>
 
<script src="/layui/layui.js"></script>
<script src="/layui/layui.all.js"></script>
<script>
    function exportExcel() {
        location.href = "/export";
    }
 
    layui.use('upload', function () {
        var $ = layui.jquery;
        var upload = layui.upload;
 
        //指定允許上傳的文件類型
        upload.render({
            elem: '#upload'
            , url: '/upload' //改成您自己的上傳接口
            , accept: 'file' //普通文件
            , exts: 'xls|xlsx'
            , done: function (res) {
                layer.msg(res.message);
                location.href = "/index";
            }
        });
    });
 
    layui.use('table', function () {
        var table = layui.table;
        table.render({
            elem: '#studentTable'
            , url: '/findAll'
            , cellMinWidth: 80 //全局定義常規單元格的最小寬度,layui 2.2.1 新增
            , cols: [[
                {field: 'id', title: 'ID', sort: true, align: 'center'}
                , {field: 'name', title: '姓名', align: 'center'} //width 支持:數字、百分比和不填寫。你還可以通過 minWidth 參數局部定義當前單元格的最小寬度,layui 2.2.1 新增
                , {field: 'photo', title: '頭像', align: 'center', templet: "#imgtmp"}
                , {field: 'tel', title: '電話', align: 'center'}
                , {field: 'sex', title: '性別', align: 'center'}
                , {field: 'address', title: '地址', align: 'center'}
                , {
                    field: 'birthday',
                    title: '出生日期',
                    align: 'center',
                    templet: "<div>{{layui.util.toDateString(d.birthday, 'yyyy-MM-dd')}}</div>"
                }
            ]]
        });
    });
</script>
<script type="text/html" id="imgtmp">
    <img src="{{'imgs/'+d.photo}}" style="width: 80px;height: 80px"/>
</script>
</body>
</html>

新建個StudentController裡面寫個跳轉方法

@RequestMapping({"/", "/index"})
    public String stuList() {
        return "studentList";
    }

效果:

正式開發

新建一個entity包,包下新建一個實體類Student

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student implements Serializable {
 
    @Excel(name = "編號")
    private Integer id;
    /**
     * width和height是導出是圖片的寬度和高度
     * type:類型,2代表圖片
     * savePath:保存的路徑(右擊保存圖片的文件夾,選Copy Path就行,這裡是存在static下的imgs中)
     */
    @Excel(name = "頭像",width = 12.0,height = 12.0,type = 2,savePath = "E:\\java\\study\\springboot_easypoi\\src\\main\\resources\\static\\imgs")
    private String photo;
    @Excel(name = "姓名")
    private String name;
    @Excel(name = "電話",width = 20.0)
    private String tel;
    @Excel(name = "性別")
    private String sex;
    @Excel(name = "地址",width = 30.0)
    private String address;
    @Excel(name = "出生日期",format = "yyyy/MM/dd",width = 15.0)
    private Date birthday;
 
}

StudentController代碼:

@Controller
@Slf4j
public class StudentController {
 
    @Autowired
    StudentService studentService;
    @Value("${upload.dir}")
    private String filePath;
 
    @RequestMapping({"/", "/index"})
    public String stuList() {
        return "studentList";
    }
 
    /**
     * 導入Excel
     * @param file 
     * @return
     */
    @RequestMapping("/upload")
    @ResponseBody
    public Result upload(MultipartFile file) {
        try {
            String originalFilename = file.getOriginalFilename();
            log.info(originalFilename);
            ImportParams params = new ImportParams();
            //標題行,如果沒有就不填,否則導入時數據會變成null
            params.setTitleRows(1);
            //頭行,例如:姓名、地址、聯繫方式  這些欄位所佔的行,佔幾行就填幾
            params.setHeadRows(1);
            //執行導入方法,返回的是一個集合(將Excel中的數據變成了pojo組成的集合)
            List<Student> students = ExcelImportUtil.importExcel(file.getInputStream(), Student.class, params);
            //調用getImgName方法獲取圖片名
            List<Student> list = getImgName(students);
            students.forEach(System.out::println);
            //調用方法將數據保存到資料庫
            studentService.saveBatch(list);
            return Result.success("上傳成功", originalFilename);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("上傳失敗");
        }
    }
 
    /**
     * 導出excel
     * @param response
     * @throws IOException
     */
    @RequestMapping("/export")
    public void exportExcel(HttpServletResponse response) throws IOException {
        //查詢出要導出的數據
        List<Student> students = studentService.findAll();
        //修改圖片的地址(改成實際的路徑)
        students.forEach(student -> {
            student.setPhoto(filePath + student.getPhoto());
        });
        //生成Excel
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("學生信息列表", "學生信息"), Student.class, students);
        response.setHeader("content-disposition", "attachment;fileName=" + URLEncoder.encode("學生信息.xls", "UTF-8"));
        ServletOutputStream outputStream = response.getOutputStream();
        workbook.write(outputStream);
        outputStream.close();
        workbook.close();
    }
    /**
     * 前端獲取信息用於展示,這裡不做分頁了
     * @return
     */
    @RequestMapping("/findAll")
    @ResponseBody
    public Map<String, Object> findAll() {
        List<Student> all = studentService.findAll();
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("msg", "獲取成功");
        map.put("count", all.size());
        map.put("data", all);
        return map;
    }
    /**
     * 獲取圖片名
     * @param students
     * @return
     */
    public List<Student> getImgName(List<Student> students) {
        students.forEach(student -> {
            String fileName = student.getPhoto().substring(student.getPhoto().lastIndexOf("\\") + 1);
            student.setPhoto(fileName);
        });
        return students;
    }
}

在寫一個配置類:(這玩意不配置都不行,不配置上傳後圖片顯示不出來,需要重啟伺服器才行)

@Configuration
public class MyImgConfig implements WebMvcConfigurer {
 
    @Value("${upload.dir}")
    private String filePath;
 
    /**
     * 不配置這個的話上傳成功後需要重啟伺服器才能訪問到圖片
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/imgs/**").addResourceLocations("file:"+filePath);
    }
}

mapper.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.lhm.mapper.StudentMapper">
 
    <insert id="savtBatch" parameterType="java.util.List">
        insert  into student(id,name,photo,address,birthday,tel,sex) values
        <foreach collection="list" item="student" index="index" separator=",">
            (#{student.id},#{student.name},#{student.photo},#{student.address},#{student.birthday},#{student.tel},#{student.sex})
        </foreach>
    </insert>
    <select id="findAll" resultType="com.lhm.entity.Student">
        select * from student
    </select>
</mapper>

測試

導入:

導出:

 

 

結論

實現了利用EasyPOI對Excel的簡單操作(導入/導出),項目源碼碼雲上有,項目地址:https://gitee.com/lihongmin5211/springboot_easypoi。寫的不好,僅供參考。

版權聲明:本文為博主原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處連結和本聲明。

本文連結:

https://blog.csdn.net/aa821198112/article/details/110733675

粉絲福利:實戰springboot+CAS單點登錄系統視頻教程免費領取

👇👇👇

感謝點讚支持下哈 

相關焦點

  • Springboot整合easyExcel導入導出Excel
    、導出excel,因此在此記錄學習一下如何使用Springboot整合easyExcel;需求:資料庫中有張user表,有個業務要求可以導入、導出「用戶名單.xls」表一、準備:創建項目:關於springboot項目如何創建這裡不再贅述,放一張項目結構圖:1、導入easyexcel、mybatis、mysql依賴
  • EasyPOI:Excel/Word 導入/導出, 註解使用,完美,便捷,高效
    ,easyPoi 功能如同名字easy,主打的功能就是容易。讓一個沒接觸過poi的人員就可以方便的寫出Excel導出,Excel導出,Excel導入,Word模板導出,通過簡單的註解和模板語言(熟悉的表達式語法),完成以前複雜的寫法;    提供下官網地址,方便查閱最新動態以及細節問題:    關於easypoi可參考http://easypoi.mydoc.io/
  • SpringBoot實現POI報表操作
    POI報表入門在mymes管理系統中,人員管理,訂單等操作需要報表的導入導出等邏輯。需求看是複雜,實際上就是對資料庫表的基本操作,本文介紹Excel的導出,下次介紹數據的導入POI報表的概述需求數碼 在企業應用開發中,Excel報表是一種最常見的報表需求。
  • 優雅 | 今天很水的文章-Excel導入導出
    前端部分這裡闡述前端部分導入,導出,生成Excel表格這裡使用的是一個js-xlsx插件,所以這裡進行嘗試。={this.downloadExl}>導出Excel</Button>這樣就完成了Excel的導出導入Excel功能實現定義相關的方法//導入excelonImportExcel = file => { // 獲取上傳的文件對象
  • Java實現文件批量導入導出實踐(兼容xls,xlsx)
    1、介紹java 實現文件的導入導出資料庫,目前在大部分系統中是比較常見的功能了,今天寫個小 demo 來理解其原理,沒接觸過的同學也可以看看參考下。目前我所接觸過的導入導出技術主要有 POI 和 iReport,poi 主要作為一些數據批量導入資料庫,iReport 做報表導出。
  • 牛逼的EasyExcel,讓Excel導入導出更加簡單,附詳細教程!
    EasyExcel在做excel導入導出的時候,發現項目中封裝的工具類及其難用,於是去gitHub上找了一些相關的框架,最終選定了EasyExcel。之前早有聽聞該框架,但是一直沒有去了解,這次藉此學習一波,提高以後的工作效率。
  • 如何使用JavaScript實現前端導入和導出excel文件
    接下來我們直接開始我們的方案實現.1. 使用JavaScript實現前端導入excel文件並自動生成可編輯的Table組件在開始實現之前, 我們先來看看實現效果.1.2 實現一鍵導入excel文件並生成table表格導入excel文件的功能我們可以用javascript原生的方式實現解析, 比如可以用fileReader這些原生api,但考慮到開發效率和後期的維護, 筆者這裡採用antd的Upload組件和XLSX來實現上傳文件並解析的功能.
  • 詳解POI的使用方法(DOM和SAX的方式)及存在的不足
    針對以上問題,阿里的 easyexcel 對 POI 進行高級封裝,提供了一套非常簡便的 API,其中,讀部分只封裝了 SAX 部分 API,事實上,使用 easyexcel 讀 excel 只會採用 SAX 方式,另外,easyexcel 重寫了 POI 對 xlsx 的解析,能夠原本一個3M的 excel 用 POI SAX 依然需要100M左右內存降低到幾M,easyexcel 的內容本文也會涉及到
  • springboot結合poi讀取Excel
    相信大家在開發過程中都會遇到讀取excel數據到資料庫裡面這個要怎麼弄這個其實有專門的工具類可以快速要我們進行寫數據  和讀取數據
  • 後端:Hutool Java 工具類庫導出 Excel,超級簡單!
    在開發應用系統的時候,導出文件是必不可放的功能。以前用過POI、easyexcel等工具的導入導出功能,但總感覺太麻煩了,代碼特別多,感覺並不是很好用。Hutool中的工具方法來自於每個用戶的精雕細琢,它涵蓋了Java開發底層代碼中的方方面面,它既是大型項目開發中解決小問題的利器,也是小型項目中的效率擔當;Hutool是項目中「util」包友好的替代,它節省了開發人員對項目中公用類和公用工具方法的封裝時間
  • Hutool Java 工具類庫導出 Excel,超級簡單!
    來源:toutiao.com/i6771298852050829835前言在開發應用系統的時候,導出文件是必不可放的功能以前用過POI、easyexcel等工具的導入導出功能,但總感覺太麻煩了,代碼特別多,感覺並不是很好用。今天給大家介紹一款新工具,java工具類庫Hutool。
  • 沒想到啊,Java操作Excel竟然這麼簡單!
    前言在工作中,使用excel表格處理數據是很常見的操作,本文就來講解下如何使用開源輪子實現下載、導入、導出的功能。1、實現已有Excel模板下載很多系統有數據批量導入的場景,因為在頁面上批量加數據時間成本太大了,但是一般導入的時候得按照一定的格式改,所以一般好的產品會先讓用戶下載一個帶有格式的文檔,然後按照格式寫好以後上傳導入,我們來實現這個功能吧!
  • SpringBoot搭配EasyExcel,一切表格就這麼完美解決了~
    github地址:https://github.com/alibaba/easyexcel# EasyExcel控制表格註解@ContentRowHeight(int):設置 row 高度,不包含表頭標記在 類上@ContentRowHeight
  • 程式設計師:java導出Excel,附帶依賴、後端代碼和前端JS
    -- Apache POI庫用於導出Excel --><dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId>
  • 【R包薈萃】Excel文件的批量導入與導出:openxlsx包實用技巧
    本期主要為大家介紹導入和導出excel文件的工具:openxlsx包,以及批量導入導出文件的一些小技巧。install.packages("openxlsx")library("openxlsx")導出excel文件使用的是write.xlsx函數,通過介紹我們可以看到該函數主要是將數據框導出為xlsx文件,同時由於excel可存在多個sheet,該函數也支持導出a list of data.frames。
  • excel圖片導出的方法
            excel教程中圖片導出的操作應該怎樣進行呢?  假設一個excel工作表中有上百張圖片,如何批量導出到某一文件夾呢?  excel圖片導出的方法如下介紹。
  • Spring Boot使用EasyExecl導出Execl
    在做後臺管理系統的時候,很多場景都會遇到Execl的導入和導出,如果在以前的話,我們基本都是用POI這個組件,不得不說,這個組件的功能確實強大,但是也有有一些弊端,比如內存佔用高、文件過大會導致OOM。後來,阿里開源的EasyExecl就能很好解決這些問題。
  • 使用SpreadJS 實現 JavaScript 中導入和導出Excel文件
    SpreadJS,正是這樣一款功能布局與Excel高度類似,無需大量代碼開發和測試即可實現數據展示、前端 Excel 導入導出、圖表面板、數據綁定等業務場景的純前端表格控制項。訪問 SpreadJS 官網了解更多產品動態:https://www.grapecity.com.cn/developer/spreadjs 使用JavaScript實現 Excel 的導入和導出通過純JavaScript,您完全可以實現導入和導出Excel文件功能,並為最終用戶提供與這些文件進行I/O交互的界面。
  • 數據科學 | pandas數據導入與導出
    當我們開始著手做一個數據分析項目時,選擇和導入數據集是第一個步驟,而導出數據雖然非必需,但有時候我們也需要保存處理或者分析後的結果,方便下次使用。在pandas中,它已經為我們提供了很多不同格式數據的導入和導出方法,下面這篇文章將具體介紹一些較為常用的方法,包括excel、csv文件以及資料庫的導入導出等。數據導入和導出是pandas中很基礎且重要的一個部分。
  • R語言數據導入與導出
    R語言數據導入與導出整這麼一個系列,還是因為學R語言時遇到過一個非常「小白友好」的網站「DataScience Made Simple」。相信很多人搜到過這個網站,或許你在意到或許並沒在意。年前試著和作者發了一封郵件,想要把他這個網站做成漢語版的帖子發在公眾號上,讓我感動的是作者團隊欣然同意。於是就想著搞這麼一個系列,能不能堅持下來還不好說……且行且珍惜吧。