JAVA导出Excel文档工具EasyExcel

介绍

EasyExcel是阿里巴巴开源的一个excel处理框架,以使用简单、节省内存著称。EasyExcel能大大减少占用内存的主要原因是在解析Excel时没有将文件数据一次性全部加载到内存中,而是从磁盘上一行行读取数据,逐个解析。

废话少说,下面以最快的方式教会大家使用easyExcel 工具

常见注解

1.@ExcelProperty

最重要的注解 , 作用于: 实体类中属性

属性值含义
value列名
index序列号
converter数据转换方式

2.@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设置自动单元格自动大小

3.@HeadFontStyle

定制标题字体格式 , 作用于类上

属性值含义
fontName设置字体名称
fontHeightInPoints设置字体高度
italic设置字体是否斜体
strikeout是否设置删除线
color设置字体颜色
typeOffset设置偏移量
underline设置下划线
charset设置字体编码
bold设置字体是否加粗

4.@HeadRowHeight

设置标题行行高 , 作用于类上

属性值含义
value设置行高,-1代表自动行高

5.@ContentStyle

设置内容格式 , 作用于类上

属性值含义
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设置自动单元格自动大小

6.@ContentFontStyle

设置内容字体样式 , 作用于类上

属性值含义
fontName字体名称
fontHeightInPoints字体高度
italic是否斜体
strikeout是否设置删除水平线
color字体颜色
typeOffset偏移量
underline下划线
bold是否加粗
charset编码格式

7.@ContentRowHeight

设置内容行高

属性值含义
value行高,-1代表自动行高

8.其他不常用注解

@ColumnWith
设置列宽 , 作用于成员属性
@ExcelIgnore
不将该字段转换成Excel
@ExcelIgnoreUnannotated
没有注解的字段都不转换

使用教程

1.引入依赖

 		<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>2.2.9</version>
        </dependency>

2.编写实体类

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@HeadStyle(horizontalAlignment = HorizontalAlignment.CENTER,verticalAlignment = VerticalAlignment.CENTER)//标题样式,垂直水平居中
@HeadFontStyle(fontName = "微软雅黑",fontHeightInPoints = 11,bold = false)//表头字体样式
@HeadRowHeight(value = 25)//表头行高
@ContentFontStyle(fontName = "微软雅黑",fontHeightInPoints = 11)//内容字体样式
@ContentRowHeight(value = 30)//内容行高
@ContentStyle(horizontalAlignment = HorizontalAlignment.CENTER,verticalAlignment = VerticalAlignment.CENTER)//内容样式,垂直水平居中
public class UserVO {
    @ExcelProperty(value = "编号",index = 0)
    private Long id;
    @ExcelProperty(value = "用户名",index = 1)
    private String username;
    @ExcelProperty(value = "用户密码",index = 2)
    private String password;
    @ExcelProperty(value = "性别",index = 3)
    private String sex;
    @ExcelProperty(value = "电话号码",index = 4)
    private String call;
    @ExcelProperty(value = "身份证号",index = 5)
    private String idCard;
    @ExcelProperty(value = "居住地址",index = 6)
    private String address;
}

3.测试类导出-非模板


@SpringBootTest
class EasyExcelDemoApplicationTests {

    @Test
    void contextLoads() {

    }
    @Test
    public void Test() throws FileNotFoundException {
        ArrayList<UserVO> list = new ArrayList<>();
        list.add(new UserVO(1L, "张三", "1234", "男", "111", "****", "北京"));
        list.add(new UserVO(2L, "李四", "1234", "女", "111", "****", "上海"));
        list.add(new UserVO(3L, "王五", "1234", "男", "111", "****", "广东"));
        list.add(new UserVO(4L, "赵六", "1234", "女", "111", "****", "深圳"));

        //模板导出设置
//        InputStream inputStream = new ClassPathResource("ExcelFile/dome文件模板.xlsx").getInputStream();//模板文件引用
        FileOutputStream out = new FileOutputStream("C:\\Files\\Excel"+".xlsx");
        EasyExcel.write(out, UserVO.class)
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())//自动加载列宽
//                .withTemplate(inputStream)//加载模板文件
                .autoCloseStream(Boolean.FALSE)
                .sheet("sheet")
                .doWrite(list);
    }

}

4.导出文件展示

在这里插入图片描述

5.测试类导出-使用模板

5.1准备文件模板

在这里插入图片描述

5.2 放在resources目录下

在这里插入图片描述

5.3修改测试类

  @Test
    public void Test() throws IOException {
        ArrayList<UserVO> list = new ArrayList<>();
        list.add(new UserVO(1L, "张三", "1234", "男", "111", "****", "北京"));
        list.add(new UserVO(2L, "李四", "1234", "女", "111", "****", "上海"));
        list.add(new UserVO(3L, "王五", "1234", "男", "111", "****", "广东"));
        list.add(new UserVO(4L, "赵六", "1234", "女", "111", "****", "深圳"));

        //模板导出设置
        InputStream inputStream = new ClassPathResource("ExcelFile/dome文件模板.xlsx").getInputStream();//模板文件引用
        FileOutputStream out = new FileOutputStream("C:\\Files\\Excel"+".xlsx");//导出文件地址
        EasyExcel.write(out, UserVO.class)
//                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                .withTemplate(inputStream)//加载模板文件
                .autoCloseStream(Boolean.FALSE)
                .sheet("sheet")
                .doWrite(list);
    }

5.4展示导出效果

在这里插入图片描述

6.以接口的形式导出文件


@Api(tags = "FileDownController", description = "文件下载接口")
@Controller
@RequestMapping(value = "/")
public class FileDownController {

    @Autowired
    private UserService userService;

    @GetMapping("download")
    public void download(HttpServletResponse response) throws IOException {
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetmL.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("fileName").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition","attachment;utf-8;filename="+fileName+".xlxs");
            response.setHeader("Access-Control-Expose-Headres","Content-Disposition");
            //查询用户列表
            List<User> userList = userService.queryAll(new UserExample());
            //表现层属性赋值
            ArrayList<UserVO> voList = new ArrayList<>();
            for (User user : userList) {
                UserVO userVO = new UserVO();
                BeanUtils.copyProperties(user,userVO);
                voList.add(userVO);
            }
            //模板导出设置
            InputStream inputStream = new ClassPathResource("ExcelFile/dome文件模板.xlsx").getInputStream();//模板文件引用
            EasyExcel.write(response.getOutputStream(),UserVO.class)
//                    .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                    .withTemplate(inputStream)
                    .autoCloseStream(Boolean.FALSE)
                    .sheet("模板")
                    .doWrite(voList);

        } catch (Exception e) {
            e.printStackTrace();
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            HashMap<String, String> map = new HashMap<>();
            map.put("status", "failure");
            map.put("message", "文件下载失败" + e.getMessage());
            response.getWriter().println(map.toString());
        }
    }
}

总结

Easyexcel 的使用方式还有很多 以最简单的方式学习 希望能够帮助到各位!

  • 4
    点赞
  • 34
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值