SpringBoot集成easyExcel导入导出Excel文件

引入依赖

<!--easyExcel-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>easyexcel</artifactId>
    <version>2.2.6</version>
</dependency>

前台代码

<a href="${ctx}/itemCategory/daoExcel">
	导出Excel
</a>

sql语句

<select id="list" resultType="ItemCategory">
    select * from item_category
</select>

注解详解

定义标题名称

@ExcelProperty
后端实现

直接在实体类字段上添加注解,设置标题名称。value可以忽略不写。

//设置标题为类目名称
@ExcelProperty(value="类目名称")
private String name;
前端页面

在这里插入图片描述

设置大标题(合并)

@ExcelProperty
后端实现

直接在字段上添加注解

@ExcelProperty({"大标题","ID"})
private Integer id;

@ExcelProperty({"大标题","类目名称"})
private String name;

@ExcelProperty({"大标题","父类ID"})
private Integer pid;

@ExcelProperty({"大标题","是否已删除"})
private Integer isDelete;
前端页面

在这里插入图片描述

设置标题所在的列数

@ExcelProperty(index= )
后端实现

直接在实体类字段上添加注解,设置标题名称。value不可忽略,必须写。

//设置标题为第一列
@ExcelProperty(value="类目名称",index=0)
private String name;
前端页面

在这里插入图片描述

设置列的长度

@ColumnWith
后端实现

直接在实体类字段上添加注解,设置列长

//设置列长为100
@ColumnWidth(100)
private String name;
前端页面

在这里插入图片描述

设置标题高度

@HeadRowHeight
后端实现

直接在实体类上添加注解,设置标题的高度

//设置标题高度为50
@HeadRowHeight(50)
public class ItemCategory implements Serializable {}
前端页面

在这里插入图片描述

设置标题背景颜色

@HeadStyle
后端实现

直接在实体类上添加注解,设置标题的背景颜色

// 头背景设置成红色 IndexedColors.RED.getIndex()
@HeadStyle(fillPatternType = FillPatternType.SOLID_FOREGROUND, fillForegroundColor = 10)
public class ItemCategory implements Serializable {}
前端页面

在这里插入图片描述

设置文本行背景颜色

@ContentStyle
后端实现

直接在实体类上添加注解,设置内容的高度

// 内容的背景设置成绿色 IndexedColors.GREEN.getIndex() 
@ContentStyle(fillPatternType = FillPatternType.SOLID_FOREGROUND, fillForegroundColor = 17)
public class ItemCategory implements Serializable { }
前端页面

在这里插入图片描述

设置某列标题下内容的背景颜色

后端实现

直接在字段上添加注解,设置内容的背景颜色

// 字符串的内容的背景设置成天蓝 IndexedColors.SKY_BLUE.getIndex()
@ContentStyle(fillPatternType = FillPatternType.SOLID_FOREGROUND, fillForegroundColor = 40)
private String name;
前端页面

在这里插入图片描述

设置标题字体样式

设置标题字体颜色

@HeadFontStyle
后端实现

直接在实体类上添加注解,设置标题的字体颜色

//设置标题颜色为青色
@HeadFontStyle(color = 11)
public class ItemCategory implements Serializable { }
前端页面

在这里插入图片描述

设置单个标题字体颜色

@HeadFontStyle
后端实现

直接在字段上添加注解,设置单个标题的字体颜色

//设置标题颜色为蓝色
@HeadFontStyle(color = 12)
private String name;
前端页面

在这里插入图片描述

设置标题字体大小

@HeadFontStyle

直接在实体类上添加注解,设置标题的字体大小

//设置标题字体大小为30
@HeadFontStyle(fontHeightInPoints=30)
public class ItemCategory implements Serializable { }
前端页面

在这里插入图片描述

设置单个标题字体大小

@HeadFontStyle

直接在字段上添加注解,设置标题的字体大小

//设置标题字体大小为30
@HeadFontStyle(fontHeightInPoints=30)
private String name;
前端页面

在这里插入图片描述

文本内容样式

设置所有列标题下内容的字体大小

@ContentFontStyle
后端实现

直接在实体类上添加注解,设置内容的字体大小

// 字符串的内容字体设置成30
@ContentFontStyle(fontHeightInPoints = 30)
public class ItemCategory implements Serializable {}
前端页面

在这里插入图片描述

设置某列标题下内容的字体大小

@ContentFontStyle
后端实现

直接在字段上添加注解,设置内容的字体大小

// 字符串的内容字体设置成30
@ContentFontStyle(fontHeightInPoints = 30)
private String name;
前端页面

在这里插入图片描述

文本行高度

@ContentRowHeight
后端实现

直接在实体类上添加注解,设置内容的高度

//设置文本行的高度为60
@ContentRowHeight(60)
public class ItemCategory implements Serializable { }
前端页面

在这里插入图片描述

设置标题字体样式

@HeadFontStyle
后端实现

直接在实体类或字段上添加注解

//设置标题字体为宋体,斜体
@HeadFontStyle(fontName = "宋体",italic = true)
public class ItemCategory implements Serializable {
前端页面

在这里插入图片描述

参数详解
参数含义
fontName设置字体名称(宋体,微软雅黑)
fontHeightInPoints设置字体高度
italic设置字体是否斜体
strikeout是否设置删除线
color设置字体颜色
typeOffset设置偏移量
underline设置下划线(可设置值 1或2,代表下划线条数)
charset设置字体编码
bold设置字体是否加粗

内容居中

@ContentRowHeight
后端实现

直接在实体类上添加注解,设置居中

//设置居中
@ContentStyle(horizontalAlignment = HorizontalAlignment.CENTER)
public class ItemCategory implements Serializable { }
前端页面

在这里插入图片描述

单列居中
后端实现

直接在实体类上添加注解,设置居中

//设置居中
@ContentStyle(horizontalAlignment = HorizontalAlignment.CENTER)
private String name;
前端页面

在这里插入图片描述

忽略某个字段

@ExcelIgnore
后端实现

直接在字段上添加注解

//导出Excel文件没有此字段,不显示
@ExcelIgnore
private String name;

设置边框

@ContentStyle
后端实现

直接在实体类上添加注解

/**
 * horizontalAlignment  设置居中
 * borderTop   设置上边框样式
 * borderBottom   设置下边框样式
 * borderLeft   设置左边框样式
 * borderRight   设置右边框样式
 */
@ContentStyle(horizontalAlignment = HorizontalAlignment.CENTER,
        borderTop = BorderStyle.THIN,
        borderBottom = BorderStyle.THIN,
        borderLeft = BorderStyle.THIN,
        borderRight = BorderStyle.THIN)
public class ItemCategory implements Serializable {
前端页面

在这里插入图片描述

BorderStyle方法详解
参数含义
NONE无边框(默认)
THIN普通实线
MEDIUM中粗实线
DASHED虚线
DOTTED点虚线
THICK大粗实线
DOUBLE双实线
HAIR虚线
MEDIUM_DASHED粗虚线
MEDIUM_DASH_DOT点、线组合
DASH_DOT_DOT点、点、线组合
MEDIUM_DASH_DOT_DOT点、点、线(加粗组合)
SLANTED_DASH_DOT点、线(模糊组合)

设置字段输出格式

后端实现

直接在字段上添加注解

//excel 用年月日的格式
@DateTimeFormat("yyyy年MM月dd日HH时mm分ss秒")
@ExcelProperty("日期标题")
private Date date;

//我想写到excel 用百分比表示
@NumberFormat("#.##%")
@ExcelProperty(value = "数字标题")
private Double doubleData;

自定义Converter转换器

转换前:

在这里插入图片描述

创建转换包 converter
后端实现
创建转换器
package com.javapandeng.converter;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.property.ExcelContentProperty;

/**
 * 自定义转换器
 * 0 未删除
 * 1 已删除
 */
public class GenderConverter implements Converter<Integer> {

    @Override
    public Class supportJavaTypeKey() {
        //对象属性类型(java中数据类型)
        return Integer.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        //CellData属性类型(Excel中数据类型)
        return CellDataTypeEnum.STRING;
    }

    /**
     * Excel数据导入到数据库
     * @param cellData
     * @param excelContentProperty
     * @param globalConfiguration
     * @return
     * @throws Exception
     */
    @Override
    public Integer convertToJavaData(CellData cellData, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        return "已删除".equals(cellData.getStringValue()) ? 1:0;
    }

    /**
     * 数据导出到Excel
     * @param integer 数据库中属性的值
     * @param excelContentProperty
     * @param globalConfiguration
     * @return
     * @throws Exception
     */
    @Override
    public CellData convertToExcelData(Integer integer, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {

        if (integer.equals(0)){
            return new CellData("未删除");
        }else if(integer.equals(1)){
            return new CellData("已删除");
        }
        return new CellData("不详");

        //如果参数只有两个采用三目运算很方便
        //return new CellData(integer.equals(1) ? "已删除" : "未删除");
    }

}
修改实体类

注解 @ExcelProperty 后添加属性 converter = GenderConverter.class

public class ItemCategory implements Serializable {

    /**
    * 是否已删除
    */
    //设置列长
    @ColumnWidth(30)
    //设置标题名称
    @ExcelProperty(value = {"商品类目表","是否已删除"},converter = GenderConverter.class)
    private Integer isDelete;
    
}
转换后页面:

在这里插入图片描述

实体类

注解@ExcelProperty(“类目名称”) //括号中内容为生成Excel文件的表头信息

/**
 * 类目
 */
// 标题背景设置成蓝色 IndexedColors.RED.getIndex()
@HeadStyle(fillPatternType = FillPatternType.SOLID_FOREGROUND, fillForegroundColor = 71)
//设置标题高度
@HeadRowHeight(40)

/**
 * horizontalAlignment  设置居中
 * borderTop   设置上边框样式
 * borderBottom   设置下边框样式
 * borderLeft   设置左边框样式
 * borderRight   设置右边框样式
 */
@ContentStyle(horizontalAlignment = HorizontalAlignment.CENTER,
        borderTop = BorderStyle.THIN,
        borderBottom = BorderStyle.THIN,
        borderLeft = BorderStyle.THIN,
        borderRight = BorderStyle.THIN)

//设置标题字体和斜体
@HeadFontStyle(fontName = "宋体",italic = true)
//设置内容字体和下划线
//@ContentFontStyle(fontName = "微软雅黑")
//设置文本内容高度
@ContentRowHeight(20)

public class ItemCategory implements Serializable {

    /**
     * 主键id
     */
    //设置列长
    @ColumnWidth(10)
    //设置标题名称
    @ExcelProperty({"商品类目表","ID"})
    private Integer id;

    /**
     * 类目名称
     */
    //设置列长
    @ColumnWidth(20)
    //设置标题名称
    @ExcelProperty({"商品类目表","类目名称"})
    @HeadFontStyle(fontName = "微软雅黑",italic = true,underline = 3)
    //设置内容字体和下划线
    //@ContentFontStyle(fontName = "微软雅黑",underline = 2)
    private String name;

    /**
     * 父id
     */
    //设置列长
    @ColumnWidth(10)
    //设置标题名称
    @ExcelProperty({"商品类目表","父类ID"})
    private Integer pid;

    /**
     * 是否已删除
     */
    //设置列长
    @ColumnWidth(30)
    //设置标题名称
    @ExcelProperty(value = {"商品类目表","是否已删除"},converter = GenderConverter.class)
    private Integer isDelete;

Controller层

//文件生成地址
String PATH = "D://";
//导出Excel
//大文件使用生成Excel (SXSSFWorkbook)
@RequestMapping("/daoExcel")
public String simpleWrite1() {

    //查询所有类目
    List<ItemCategory> list = itemCategoryService.list();

    String fileName = PATH + "成绩表.xlsx";
    // 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭
    // 如果这里想使用03 则 传入excelType参数即可
    EasyExcel.write(fileName, ItemCategory.class).sheet("模板sheet").doWrite(list);

    System.out.println("数据导出成功");

    return "redirect:/itemCategory/findAll";

}

@ContentStyle中的所有参数

@HeadStyle 也可用
参数含义
dataFormat日期格式
hidden设置单元格使用此样式隐藏
locked设置单元格使用此样式锁定
quotePrefix在单元格前面增加`符号,数字或公式将以字符串形式展示
horizontalAlignment设置是否水平居中
wrapped设置文本是否应换行。将此标志设置为true通过在多行上显示使单元格中的所有内容可见
verticalAlignment设置是否垂直居中
rotation设置单元格中文本旋转角度。03版本的Excel旋转角度区间为-90°90°,07版本的Excel旋转角度区间为0°180°
indent设置单元格中缩进文本的空格数
borderLeft设置左边框的样式
borderRight设置右边框样式
borderTop设置上边框样式
borderBottom设置下边框样式
leftBorderColor设置左边框颜色
rightBorderColor设置右边框颜色
topBorderColor设置上边框颜色
bottomBorderColor设置下边框颜色
fillPatternType设置填充类型
fillBackgroundColor设置背景色
fillForegroundColor设置前景色
shrinkToFit设置自动单元格自动大小

注解 fillForegroundColor 对应的颜色值

在这里插入图片描述



       每个人的内心深处都会保留着一份悲观色彩,只是因为现实的残酷,人心的难测,所以才会用层层面具遮盖起自己真实的一面,没有人可以从容的面对一切经历,也没有人可以淡定的去处理一切遭遇。
  • 8
    点赞
  • 58
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: Spring Boot 是一个用于创建基于 Spring 框架的独立、生产级别的应用程序的框架。EasyExcel 是一个基于 Java 的开源框架,可以方便地读写 Excel 文件。使用 EasyExcel 可以轻松地进行 Excel 文件导入导出,非常适合在 Spring Boot 项目中使用。 下面是在 Spring Boot 项目中使用 EasyExcel 进行 Excel 文件导入导出的基本步骤: 1. 添加 EasyExcel 依赖 在项目的 pom.xml 文件中添加 EasyExcel 依赖: ```xml <dependency> <groupId>com.alibaba</groupId> <artifactId>easyexcel</artifactId> <version>2.2.10</version> </dependency> ``` 2. 编写 Excel 导出代码 使用 EasyExcel 可以非常方便地进行 Excel 文件导出。例如,以下代码可以将一个 List 对象导出Excel 文件: ```java // 定义 Excel 表头 List<List<String>> head = new ArrayList<>(); head.add(Arrays.asList("姓名", "年龄")); // 定义 Excel 数据 List<List<Object>> data = new ArrayList<>(); data.add(Arrays.asList("张三", 18)); data.add(Arrays.asList("李四", 20)); data.add(Arrays.asList("王五", 22)); // 导出 Excel 文件 String fileName = "example.xlsx"; String sheetName = "Sheet1"; EasyExcel.write(fileName).sheet(sheetName).head(head).sheet().doWrite(data); ``` 3. 编写 Excel 导入代码 使用 EasyExcel 进行 Excel 文件导入也非常方便。例如,以下代码可以从 Excel 文件中读取数据并转换为一个 List 对象: ```java // 定义读取 Excel 文件的监听器 public class ExcelListener extends AnalysisEventListener<Object> { private List<Object> data = new ArrayList<>(); @Override public void invoke(Object object, AnalysisContext context) { data.add(object); } @Override public void doAfterAllAnalysed(AnalysisContext context) {} public List<Object> getData() { return data; } } // 读取 Excel 文件 String fileName = "example.xlsx"; ExcelListener listener = new ExcelListener(); EasyExcel.read(fileName, listener).sheet().doRead(); List<Object> data = listener.getData(); ``` 4. 将 Excel 文件导入到数据库 读取 Excel 文件之后,可以将数据存入数据库中。以下代码演示了将读取的 Excel 文件中的数据存入 MySQL 数据库的过程: ```java // 定义实体类 @Data public class Person { private String name; private Integer age; } // 保存数据到数据库 List<Person> persons = new ArrayList<>(); for (Object obj : data) { List<Object> row = (List<Object>) obj; Person person = new Person(); person.setName((String) row.get(0)); person.setAge((Integer) row.get(1)); persons.add(person); } personRepository.saveAll(persons); ``` 以上就是使用 EasyExcel 进行 Excel 文件导入导出的基本步骤。根据实际需求,可以对以上代码进行相应的修改和扩展。 ### 回答2: Spring Boot 是一个开源的Java开发框架,可以帮助开发人员快速构建基于Spring的应用程序。EasyExcel 是一种基于JavaExcel读写工具,它提供了简单便捷的API,可以方便地实现Excel导入导出功能。 在Spring Boot中使用EasyExcel进行导入导出操作非常简单。首先,我们需要在pom.xml文件中添加EasyExcel的依赖项,以便可以使用它的功能。然后,我们可以创建一个Controller类来处理导入导出的请求。 对于导入操作,我们可以使用EasyExcel提供的@ExcelProperty注解来标记实体类的字段与Excel的列的映射关系。然后,我们可以使用EasyExcel的read方法来读取Excel文件,并将数据转换为实体类对象。最后,我们可以对读取到的数据进行相应的业务操作,比如存储到数据库中。 对于导出操作,我们可以使用EasyExcel的@ExcelProperty注解标记实体类的字段,并使用EasyExcel的write方法来将实体类列表写入Excel文件。我们可以通过指定文件路径或输出流的方式进行导出。 除了基本的导入导出功能,EasyExcel还提供了一些高级特性,比如读取大文件、多sheet处理、自定义读写处理器等。这些特性可以帮助我们更好地应对复杂的Excel导入导出需求。 总而言之,Spring Boot结合EasyExcel提供了一种简单快捷的方式来实现Excel导入导出功能。无论是处理简单的Excel文件还是应对复杂的导入导出需求,Spring Boot和EasyExcel都能够提供强大的支持。 ### 回答3: Spring Boot 是一种简化了开发过程的Java框架,而EasyExcel是一种用于操作Excel文件的开源库。通过结合使用Spring Boot和EasyExcel,我们可以方便地实现Excel文件导入导出功能。下面将详细介绍如何使用Spring Boot和EasyExcel来实现导入导出功能。 首先,我们需要在Spring Boot的项目中引入EasyExcel的依赖。在pom.xml文件中添加以下依赖: ``` <dependency> <groupId>com.alibaba</groupId> <artifactId>easyexcel</artifactId> <version>2.2.6</version> </dependency> ``` 接着,我们可以创建一个Controller类来处理导入导出的请求。在该类中,我们可以定义两个方法,一个用于导入Excel文件,另一个用于导出Excel文件。 对于导入功能,我们可以使用EasyExcel提供的`read()`方法来读取Excel文件,并将读取到的数据转换为一个List对象。以下是一个简单的导入方法的示例代码: ```java @PostMapping("/import") public void importExcel(@RequestParam("file") MultipartFile file) throws IOException { List<DataDTO> dataList = EasyExcel.read(file.getInputStream()).head(DataDTO.class).sheet().doReadSync(); // 处理导入的数据 } ``` 对于导出功能,我们可以使用EasyExcel提供的`write()`方法来创建一个Excel文件,并将数据写入到该文件中。以下是一个简单的导出方法的示例代码: ```java @GetMapping("/export") public void exportExcel(HttpServletResponse response) throws IOException { List<DataDTO> dataList = getDataList(); // 获取导出的数据 response.setContentType("application/vnd.ms-excel"); response.setCharacterEncoding("utf-8"); response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("data.xlsx", "utf-8")); EasyExcel.write(response.getOutputStream()).sheet("Data").doWrite(dataList); } ``` 在上述代码中,我们首先获取需要导出的数据(getDataList()方法需要根据实际情况实现),然后设置响应头信息,最后使用`write()`方法将数据写入到响应的输出流中。 通过以上步骤,我们在Spring Boot项目中成功实现了使用EasyExcel进行Excel文件导入导出功能。我们可以根据具体需求对导入的数据进行处理,也可以根据实际情况设置导出文件的格式和名称。同时,EasyExcel还提供了更多的功能和选项,如设置表头、导入数据校验等,可以根据具体需求进行使用。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值