java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > 使用EasyExcel实现excel文件读写

Java使用EasyExcel实现对excel文件的读写方式

作者:lfyyyyy

这篇文章主要介绍了Java使用EasyExcel实现对excel文件的读写方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

提示:这里可以添加本文要记录的大概内容:

在学习Java中难免会有对文件的读写操作,像word文档、pdf文件以及excel表。这些读写操作都大差不差,接下来为大家讲解一下Java对excel表的读写操作。

提示:以下是本篇文章正文内容,下面案例可供参考

一、EasyExcel是什么?

EasyExcel是阿里巴巴开源的一款基于Java语言的简单、高效、功能强大的Excel读写工具库。

它提供了简单易用的API,可以帮助Java开发者在项目中轻松地进行Excel文件的读写操作,支持读取和写入Excel文件,同时支持常见的Excel格式,如.xls和.xlsx。

EasyExcel具有以下主要特点:

总的来说,EasyExcel是一款功能强大且易于使用的Java Excel处理工具库,被广泛应用于各种Java项目中,特别是对Excel文件读写操作比较频繁的业务场景。

官方文档地址EasyExcel

二、使用步骤

1.引入库

我们创建maven项目,在pom.xml文件中添加依赖:

       <!--easy excel依赖-->
       <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>3.3.4</version>
        </dependency>

        <!--lombok依赖  用来生成getter/setter/构造函数的-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.30</version>
        </dependency>

2.创建实体类

代码如下(示例):

@Data   //提供getter/setter
@NoArgsConstructor  //无参构造
@AllArgsConstructor  //含有全部参数的构造
public class Goods {

    @ExcelIgnore   //easyexcel注解 表示读写excel表忽略此列
    int id;

    @ExcelProperty("编码")   //easyexcel注解 表示读写excel表对列名为“编码”进行读写
    String code;

    @ExcelProperty("名称")
    String name;

    @ExcelProperty("价格")
    double price;

    @ExcelProperty("库存")
    int num;

    @ExcelProperty("重量")
    double weight;

    @ExcelProperty("cpu")
    String cpu;

    @ExcelProperty("内存")
    String memory;

    @ExcelProperty("机身内存")
    String bodyMemory;

    @ExcelIgnore
    String createTime;

    @ExcelIgnore
    String updateTime;

    @ExcelIgnore
    String categoryCode;
}

3.建立数据库

因为我们在读写操作时需要有一定的数据源才能把读写操作更加明显。

/*
 Navicat Premium Data Transfer

 Source Server         : RpWn
 Source Server Type    : MySQL
 Source Server Version : 50735 (5.7.35)
 Source Host           : localhost:3306
 Source Schema         : demo

 Target Server Type    : MySQL
 Target Server Version : 50735 (5.7.35)
 File Encoding         : 65001

 Date: 26/03/2024 16:39:43
*/

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for goods
-- ----------------------------
DROP TABLE IF EXISTS `goods`;
CREATE TABLE `goods`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `code` varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `name` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `price` decimal(10, 2) NULL DEFAULT NULL,
  `num` int(11) NULL DEFAULT 0,
  `weight` decimal(10, 2) NULL DEFAULT NULL,
  `cpu` varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `memory` varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `bodyMemory` varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `createTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  `updateTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `isdel` bit(1) NULL DEFAULT b'0',
  `categoryCode` varchar(7) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 297 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = DYNAMIC;

-- ----------------------------
-- Records of goods
-- ----------------------------
INSERT INTO `goods` VALUES (10, '8JxeXVKZkP', '11213', 342.25, 632, 891.65, 'jwkMVVsIsf', '2TuPtOEmMY', 'Ywp6WoBoTl', '2024-03-13 15:15:44', '2024-03-15 19:46:52', b'0', '10202');
INSERT INTO `goods` VALUES (11, '123', '123', 23.20, 32, 213.40, '21', '@', '43', '2024-03-13 16:09:48', '2024-03-15 19:46:52', b'1', '10203');
INSERT INTO `goods` VALUES (12, '123', '123', 23.20, 32, 213.40, '21', '@', '43', '2024-03-13 16:15:57', '2024-03-15 19:46:52', b'0', '10204');
INSERT INTO `goods` VALUES (13, '123', '123', 23.20, 32, 213.40, '21', '@', '43', '2024-03-13 17:14:59', '2024-03-15 19:46:52', b'0', '10301');
INSERT INTO `goods` VALUES (14, '123', '123', 23.20, 32, 213.40, '21', '@', '43', '2024-03-15 14:53:58', '2024-03-15 19:46:52', b'0', '10302');
INSERT INTO `goods` VALUES (15, '123', '123', 23.20, 32, 213.40, '21', '@', '43', '2024-03-15 15:00:08', '2024-03-15 19:46:52', b'0', '10401');
INSERT INTO `goods` VALUES (16, '123', '123', 23.20, 32, 213.40, '21', '@', '43', '2024-03-15 15:00:13', '2024-03-15 19:46:52', b'1', '10402');
INSERT INTO `goods` VALUES (17, '123', '12', 1110.00, 210, 11.00, '12', '21', '32 b', '2024-03-15 17:55:20', '2024-03-15 19:46:52', b'0', '1010101');
INSERT INTO `goods` VALUES (18, 'qq', '112', 1.00, 1, 1.00, '1', '1', '123', '2024-03-15 18:50:12', '2024-03-15 19:46:52', b'0', '1010102');
INSERT INTO `goods` VALUES (19, '11213', '无敌暴龙战神', 110.00, 10, 13111.00, '1451', '142', '1423', '2024-03-15 19:09:53', '2024-03-15 19:46:52', b'0', '1010103');
INSERT INTO `goods` VALUES (20, 'GCAn5xkhVy', 'ambi-Raspberry', 91.01, 407, 180.74, 'Hkm7kRcl6I', 'FHvqdmS6SJ', 'ILGoivG3bp', '2024-03-15 19:46:41', '2024-03-15 19:46:52', b'0', '1010201');
INSERT INTO `goods` VALUES (21, 'TeygdLkvdh', 'vrape elite', 990.81, 625, 411.26, 'gYQj6zvQiS', 'kMVZXbpAUV', 'kHnRT7ksaS', '2024-03-15 19:46:41', '2024-03-15 19:46:52', b'0', '1010202');
INSERT INTO `goods` VALUES (22, 'LNwjlXxjNr', 'omni-Apcle', 960.91, 564, 515.32, 'LQI00Ov0N5', '6duf1gDWfl', 'FE3EnBhCm3', '2024-03-15 19:46:41', '2024-03-15 19:46:52', b'0', '1010203');
INSERT INTO `goods` VALUES (23, 'jgP7RNAxIm', 'Cherry premium', 765.80, 229, 922.03, 'RphJtpk0yq', 'bwkpOP0xrf', 'YYktTwd8RL', '2024-03-15 19:46:41', '2024-03-15 19:46:52', b'0', '1010301');
INSERT INTO `goods` VALUES (24, 'Vuwp9T6Xoc', 'Strawberry premium', 327.73, 207, 483.71, 'dJptxXoG3g', '7W9aNT3YIw', 'ySVvlIl9bS', '2024-03-15 19:46:41', '2024-03-15 19:46:52', b'0', '1010302');
INSERT INTO `goods` VALUES (25, 'XNfAc4CGcc', 'ultra-Mahgo', 609.87, 949, 386.22, '8hfxX9sWKL', 'uif9nrBYg6', 'N6NFLIKMHS', '2024-03-15 19:46:41', '2024-03-15 19:46:52', b'0', '1020101');
INSERT INTO `goods` VALUES (26, 'jC6omI1LRF', 'Orange', 702.47, 247, 380.92, 'JF47lnS0Ln', '2NQDhyOepP', 'TtQxIBYvJC', '2024-03-15 19:46:41', '2024-03-15 19:46:52', b'0', '1020102');
INSERT INTO `goods` VALUES (27, 'ToQNHEcFF7', 'Rambutan elite', 166.33, 471, 534.81, 'o8kHT3DYTm', 'PZYUKx2mKE', '1K3z3PEion', '2024-03-15 19:46:41', '2024-03-15 19:46:52', b'0', '1030101');
INSERT INTO `goods` VALUES (28, 'DOqVaUOxxX', 'omni-Manao', 483.54, 964, 432.00, 'nZq8jcRRZc', 'd6GPizay4L', 'evU3hBvO75', '2024-03-15 19:46:41', '2024-03-15 19:46:52', b'0', '1030102');
INSERT INTO `goods` VALUES (29, 'yktNTOYnCB', 'Pluots', 92.17, 432, 350.00, 'xLyjlwWZyr', 'shIVVKRoyq', 'CQRiONav9n', '2024-03-15 19:46:41', '2024-03-15 19:47:00', b'0', '101');
INSERT INTO `goods` VALUES (30, 'h363yMOkgx', 'Strawberry', 994.03, 356, 693.20, 'EdvpRzfBx7', 'wOHno9Jz9i', 'UBuS5mBqc1', '2024-03-15 19:46:41', '2024-03-15 19:47:00', b'0', '102');
INSERT INTO `goods` VALUES (31, 'rEaMNLqLeC', 'Cherry', 379.39, 662, 808.42, 'citpl2UEcL', 'AGSi2euAgD', 'lv4HBC865S', '2024-03-15 19:46:41', '2024-03-15 19:47:00', b'0', '103');
INSERT INTO `goods` VALUES (32, 'EH19SlGYZj', 'Rambutan', 846.04, 75, 746.55, 'GXQMiPnPAJ', 'Xsn1EykF2W', '8r9fQIvV2m', '2024-03-15 19:46:41', '2024-03-15 19:47:00', b'0', '104');
INSERT INTO `goods` VALUES (33, '1RZU3Tqk7x', 'Grape', 13.95, 823, 216.07, '874XE6Vfn8', 'v4QVOstgxz', 'UTpwHaMJbJ', '2024-03-15 19:46:41', '2024-03-15 19:47:00', b'0', '10101');
INSERT INTO `goods` VALUES (34, 'RSWbeUZiV0', 'Orange', 28.17, 774, 390.75, '5XymcnPLNI', 'xPkIHsRb87', '5wsV0pY08i', '2024-03-15 19:46:41', '2024-03-15 19:47:00', b'0', '10102');
INSERT INTO `goods` VALUES (35, 'i63Ka18rPr', 'Pluots premium', 697.21, 637, 254.10, 'XTvctbht7g', 'SqmbRxUj93', 'JT0I7jpIKz', '2024-03-15 19:46:41', '2024-03-15 19:47:00', b'0', '10103');
INSERT INTO `goods` VALUES (36, 'juAaluEVw2', 'Plzots mini', 820.39, 975, 877.59, 'aeKNUJfrMJ', 'vovuBeT0fd', 'xpYxNtS6g7', '2024-03-15 19:46:41', '2024-03-15 19:47:00', b'0', '10104');
INSERT INTO `goods` VALUES (37, 'ILMzyZAI5P', 'omni-Apple', 522.76, 391, 861.30, 'yek34RVacI', 'gmiHMwtOOa', 'Zz78bgunty', '2024-03-15 19:46:41', '2024-03-15 19:47:00', b'0', '10201');
INSERT INTO `goods` VALUES (38, 'BbUqlhempM', 'apple mini', 437.47, 997, 494.17, 'hXHUcRt2SU', 'bSRStT87H0', 'sxrB9HrjoA', '2024-03-15 19:46:41', '2024-03-15 19:47:00', b'0', '10202');
INSERT INTO `goods` VALUES (39, 'q4a9NkNyxf', 'Orange', 480.17, 63, 884.94, 'kyOD6tFQXP', 'fZvn2xuQjj', '89Tq4sfgCz', '2024-03-15 19:46:41', '2024-03-15 19:47:00', b'0', '10203');
INSERT INTO `goods` VALUES (40, 'fOjYWHi8ua', 'Grape premium', 650.66, 566, 841.37, 'G8oRswf3KW', 'PrKkVnkD7O', 'HsowQhNHog', '2024-03-15 19:46:41', '2024-03-15 19:47:00', b'0', '10204');
INSERT INTO `goods` VALUES (41, 'S4afyOy3lL', 'ambi-Rarpberry', 362.22, 153, 235.46, 'ZdI09ZjEu1', 'nzK0o8QcNC', 'vIdsY2B2S2', '2024-03-15 19:46:41', '2024-03-15 19:47:00', b'0', '10301');
INSERT INTO `goods` VALUES (42, '31u5gpIuc2', 'Mango', 113.45, 227, 250.62, 'XpjLaU4EHt', 'yJj1BCfGoc', 'N1Ao1bU0RP', '2024-03-15 19:46:41', '2024-03-15 19:47:00', b'0', '10302');
INSERT INTO `goods` VALUES (43, '4g51Wc0jcB', 'Pluots pro', 303.28, 795, 89.98, 'Acqc5kHe2p', 'CRTHYHLP5B', 'liTcPXWhdq', '2024-03-15 19:46:41', '2024-03-15 19:47:00', b'0', '10401');
INSERT INTO `goods` VALUES (44, '84ZehUTLjD', 'Raspberry', 539.56, 306, 587.33, 'Dx7KhBN5U9', 'ZqqZXTloyl', 'ux69ulYjju', '2024-03-15 19:46:41', '2024-03-15 19:47:00', b'0', '10402');
INSERT INTO `goods` VALUES (45, 'umYoiRRix7', 'Chdrry', 103.36, 459, 570.75, 'iZPw211fEu', 'Nbnd5HrBHp', 'QSwseMu3Ej', '2024-03-15 19:46:41', '2024-03-15 19:47:00', b'0', '1010101');
INSERT INTO `goods` VALUES (46, 'IuvvAf5EsI', 'ultra-Maggo', 628.76, 494, 765.33, '2w7BLgJvQu', 'Oc1xPdT0yd', 'qWWHjE1UTc', '2024-03-15 19:46:41', '2024-03-15 19:47:00', b'0', '1010102');
INSERT INTO `goods` VALUES (47, '1Hwkg09RUl', 'Pluots', 745.62, 138, 601.36, 'SRzYABnSID', 'TCvzR1TAtc', 'Vxvndc4dj3', '2024-03-15 19:46:41', '2024-03-15 19:47:00', b'0', '1010103');
INSERT INTO `goods` VALUES (48, '9LSHUqpgP0', 'Cherry pro', 453.36, 780, 583.65, 'bQyrF7GWhe', '1DhzUp6X7p', '0AWyRCmycj', '2024-03-15 19:46:41', '2024-03-15 19:47:00', b'0', '1010201');
INSERT INTO `goods` VALUES (49, 'TP5PbkIcW7', 'Grahe', 357.14, 796, 755.99, 'FzmR1fQm0H', 'HGxmRasHEy', 'mleG0TTni5', '2024-03-15 19:46:41', '2024-03-15 19:47:00', b'0', '1010202');

SET FOREIGN_KEY_CHECKS = 1;

4.先建两个excel表

在这里插入图片描述

可以像我一样放在项目里,当然你放的位置和文件名都随意 。

5.书写Mapper

<!--将数据库数据导出到excel文件的映射-->
    <select id="queryAll" resultType="goods">
        select *
        from goods
        where isdel = 0
    </select>
<!--将excel文件数据导入到数据库的映射  使用foreach批量添加-->
    <insert id="addManyGoods">
        insert into goods (code, name, price, num, weight, cpu, memory, bodyMemory)
        values
        <foreach collection="list" item="it" separator=",">
            (#{it.code},#{it.name},#{it.price},#{it.num},#{it.weight},#{it.cpu},#{it.memory},#{it.bodyMemory})
        </foreach>
    </insert>

6.书写测试类

简单使用测试类来进行测试。

    SqlSession session = FactoryUtil.getFactory().openSession(true);
    GoodsMapper goodsMapper = session.getMapper(GoodsMapper.class);

    private List<Goods> data() {
        //调用方法获取数据库数据
        return goodsMapper.queryAll();
    }

    
    //写入excel操作
    public void testSimpleWrite() {

        String fileName = ".....\\Shop\\src\\main\\excel\\Goods.xlsx";
        EasyExcel.write(fileName, Goods.class)
                .sheet("模板")
                .doWrite(this::data);

    }




    //读excel表,写入数据库操作
    public void testSimpleRead() {
        String fileName = ".......\\Shop\\src\\main\\excel\\Goods2.xlsx";
        EasyExcel.read(fileName, Goods.class, new PageReadListener<Goods>(dataList -> {
            System.out.println(dataList.size());
            int n = goodsMapper.addManyGoods(dataList);
              System.out.println(n);
        })).sheet().doRead();
    }

总结

EasyExcel还有很多的属性,下方是为大家总结的常用api。

总的来说,EasyExcel作为一款功能丰富的Excel处理工具库,具有许多属性和功能,可以满足各种不同场景下的Excel文件读写需求,并且易于使用和扩展。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文