SpringBoot导出Excel实现

一、Excel导出概述

在开发中,有时候需要将数据导出为Excel格式,在Excel中进行查看、分析、汇总等操作。对于Java Web开发者而言,一款好用的Excel导出插件是必不可少的。在SpringBoot中,我们可以使用EasyExcel、POI和JExcel等插件来实现Excel导出。

二、EasyExcel实现Excel导出

EasyExcel是基于POI封装的一款Java解析和生成Excel的开源项目,具有高效、易用、功能强大的特点。EasyExcel支持大文件读写、百万数据导出、快速生成Excel样式等功能。下面介绍一下在SpringBoot中如何实现Excel导出。

1、引入EasyExcel依赖

我们可以通过在pom.xml文件中引入如下EasyExcel的maven依赖来使用EasyExcel插件:

    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>easyexcel</artifactId>
        <version>2.1.6-beta5</version>
    </dependency>

2、定义实体类

假设我们要将一个人的信息导出为Excel表格,我们首先需要定义一个实体类:

    public class Person {
        private String name;
        private Integer age;
        private String email;
        //省略get、set方法
    }

3、创建ExcelWriter对象并写入数据

接下来是最关键的一步,即创建ExcelWriter对象并写入数据。我们可以通过如下代码来实现:

    @RequestMapping("/export")
    public void export(HttpServletResponse response) throws IOException {
        List list = new ArrayList();
        //省略添加数据操作
        String fileName = "person.xlsx";
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName,"UTF-8"));
        response.setContentType("multipart/form-data");
        EasyExcel.write(response.getOutputStream(), Person.class).sheet("sheet").doWrite(list);
    }

4、代码示例

下面是完整的Excel导出代码示例,其中还包括了生成Excel样式的操作:

    @RequestMapping("/export")
    public void export(HttpServletResponse response) throws IOException {
        // 数据准备
        List list = new ArrayList();
        Person person = new Person();
        person.setName("张三");
        person.setAge(20);
        person.setEmail("zhangsan@demo.com");
        list.add(person);

        // 生成Excel样式
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();
        WriteSheet writeSheet = EasyExcel.writerSheet("sheet").build();
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        headWriteCellStyle.setFillForegroundColor(IndexedColors.LIGHT_BLUE.getIndex());
        WriteFont headWriteFont = new WriteFont();
        headWriteFont.setFontHeightInPoints((short) 14);
        headWriteCellStyle.setWriteFont(headWriteFont);
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        WriteFont contentWriteFont = new WriteFont();
        contentWriteFont.setFontHeightInPoints((short) 12);
        contentWriteCellStyle.setWriteFont(contentWriteFont);

        // 写入数据
        excelWriter.write(list, writeSheet, new TableWriteData(), new CellWriteData(headWriteCellStyle,contentWriteCellStyle));

        // 输出Excel
        excelWriter.finish();
        response.setContentType("multipart/form-data");
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("person.xlsx","UTF-8"));
    }

三、POI实现Excel导出

POI(Poor Obfuscation Implementation)是由Apache组织提供的用于操作Microsoft Office格式文件的Java API。下面介绍一下在SpringBoot中如何实现Excel导出。

1、引入POI依赖

我们可以通过在pom.xml文件中引入如下POI的maven依赖来使用POI插件:

    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi</artifactId>
        <version>4.0.1</version>
    </dependency>

2、创建Excel对象

接下来是最关键的一步,即创建Excel对象。我们可以通过如下代码来实现:

    Workbook workbook = new XSSFWorkbook();//或者new HSSFWorkbook()
    Sheet sheet = workbook.createSheet("sheet");
    Row row = sheet.createRow(0);
    row.createCell(0).setCellValue("姓名");
    row.createCell(1).setCellValue("年龄");
    row.createCell(2).setCellValue("邮箱");

3、写入数据并导出

我们可以通过如下代码将数据写入Excel中:

    int rowIndex = 1;
    for (Person person : list) {
        Row nRow = sheet.createRow(rowIndex++);
        nRow.createCell(0).setCellValue(person.getName());
        nRow.createCell(1).setCellValue(person.getAge());
        nRow.createCell(2).setCellValue(person.getEmail());
    }

接下来是导出的代码:

    String fileName = "person.xlsx";
    response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName,"UTF-8"));
    workbook.write(response.getOutputStream());
    workbook.close();

4、代码示例

下面是完整的Excel导出代码示例:

    @RequestMapping("/export")
    public void export(HttpServletResponse response) throws IOException {
        List list = new ArrayList();
        Person person = new Person();
        person.setName("张三");
        person.setAge(20);
        person.setEmail("zhangsan@demo.com");
        list.add(person);

        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("sheet");
        Row row = sheet.createRow(0);
        row.createCell(0).setCellValue("姓名");
        row.createCell(1).setCellValue("年龄");
        row.createCell(2).setCellValue("邮箱");
        int rowIndex = 1;
        for (Person person : list) {
            Row nRow = sheet.createRow(rowIndex++);
            nRow.createCell(0).setCellValue(person.getName());
            nRow.createCell(1).setCellValue(person.getAge());
            nRow.createCell(2).setCellValue(person.getEmail());
        }

        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("person.xlsx","UTF-8"));
        workbook.write(response.getOutputStream());
        workbook.close();
    }

四、JExcel实现Excel导出

JExcel是一款功能强大的Excel处理库,支持Excel 97/2000/XP/2003格式,使用JExcel可以实现单元格样式设置、单元格合并、单元格格式转换以及数据写入等功能。下面介绍一下在SpringBoot中如何实现Excel导出。

1、引入JExcel依赖

我们可以通过在pom.xml文件中引入如下JExcel的maven依赖来使用JExcel插件:

    <dependency>
        <groupId>net.sourceforge.jexcelapi</groupId>
        <artifactId>jxl</artifactId>
        <version>2.6.12</version>
    </dependency>

2、创建Excel对象

接下来是最关键的一步,即创建Excel对象。我们可以通过如下代码来实现:

    WritableWorkbook workbook = Workbook.createWorkbook(response.getOutputStream());
    WritableSheet sheet = workbook.createSheet("Sheet1", 0);
    Label label1 = new Label(0, 0, "姓名");
    Label label2 = new Label(1, 0, "年龄");
    Label label3 = new Label(2, 0, "邮箱");
    sheet.addCell(label1);
    sheet.addCell(label2);
    sheet.addCell(label3);

3、写入数据并导出

我们可以通过如下代码将数据写入Excel中:

    int rowIndex = 1;
    for (Person person : list) {
        Label labelN1 = new Label(0, rowIndex, person.getName());
        Label labelN2 = new Label(1, rowIndex, person.getAge().toString());
        Label labelN3 = new Label(2, rowIndex, person.getEmail());
        sheet.addCell(labelN1);
        sheet.addCell(labelN2);
        sheet.addCell(labelN3);
        rowIndex++;
    }

接下来是导出的代码:

    workbook.write();
    workbook.close();
    response.flushBuffer();

4、代码示例

下面是完整的Excel导出代码示例:

    @RequestMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        List list = new ArrayList();
        Person person = new Person();
        person.setName("张三");
        person.setAge(20);
        person.setEmail("zhangsan@demo.com");
        list.add(person);

        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("person.xls","UTF-8"));
        WritableWorkbook workbook = Workbook.createWorkbook(response.getOutputStream());
        WritableSheet sheet = workbook.createSheet("Sheet1", 0);
        Label label1 = new Label(0, 0, "姓名");
        Label label2 = new Label(1, 0, "年龄");
        Label label3 = new Label(2, 0, "邮箱");
        sheet.addCell(label1);
        sheet.addCell(label2);
        sheet.addCell(label3);
        int rowIndex = 1;
        for (Person person : list) {
            Label labelN1 = new Label(0, rowIndex, person.getName());
            Label labelN2 = new Label(1, rowIndex, person.getAge().toString());
            Label labelN3 = new Label(2, rowIndex, person.getEmail());
            sheet.addCell(labelN1);
            sheet.addCell(labelN2);
            sheet.addCell(labelN3);
            rowIndex++;
        }

        workbook.write();
        workbook.close();
        response.flushBuffer();
    }

原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/196886.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
小蓝小蓝
上一篇 2024-12-03 13:26
下一篇 2024-12-03 13:26

相关推荐

  • 从ga角度解读springboot

    springboot作为目前广受欢迎的Java开发框架,其中的ga机制在整个开发过程中起着至关重要的作用。 一、ga是什么 ga即Group Artifacts的缩写,它是Mave…

    编程 2025-04-29
  • 为什么不能用Microsoft Excel进行Python编程?

    Microsoft Excel是一个广泛使用的数据分析工具,但是它不能直接用于Python编程。这是因为Microsoft Excel并不是一个编程工具,它的主要功能是进行数据处理…

    编程 2025-04-29
  • 基尼系数Excel计算模板

    这篇文章将介绍基尼系数Excel计算模板,为大家详细阐述如何使用Excel进行基尼系数的计算。 一、模板下载及导入 首先需要下载基尼系数的Excel计算模板,可以在Excel中通过…

    编程 2025-04-28
  • SpringBoot Get方式请求传参用法介绍

    本文将从以下多个方面对SpringBoot Get方式请求传参做详细的阐述,包括URL传参、路径传参、请求头传参、请求体传参等,帮助读者更加深入地了解Get请求方式下传参的相关知识…

    编程 2025-04-27
  • SpringBoot如何设置不输出Info日志

    本篇文章将带您了解如何在SpringBoot项目中关闭Info级别日志输出。 一、为什么要关闭Info日志 在开发中,我们经常会使用Log4j、Logback等框架来输出日志信息,…

    编程 2025-04-27
  • 使用ReoGrid操作Excel的WPf应用

    本文将详细阐述如何使用ReoGrid来操作Excel,重点介绍在WPF应用程序中使用ReoGrid的方法及注意点。 一、ReoGrid简介 ReoGrid是一个基于.NET的开源组…

    编程 2025-04-27
  • 解决springboot中scanBasePackages无法读取子包的问题

    在使用springboot搭建项目时,可能会遇到scanBasePackages无法读取子包的问题。本文将从几个方面详细阐述如何解决这个问题。 一、问题描述 在使用Springbo…

    编程 2025-04-25
  • Excel日期函数

    Excel是当前企业和个人使用非常广泛的办公软件之一。其中的日期函数可以用于处理各种涉及日期和时间的任务。本文将从不同的方面介绍Excel日期函数,帮助读者深入了解和熟练使用日期函…

    编程 2025-04-25
  • SpringBoot请求参数绑定

    解答:SpringBoot请求参数绑定是指将HTTP请求中的参数与Controller方法的参数绑定起来,使得参数的传递变得简单和方便。下面我们将从多个方面对SpringBoot请…

    编程 2025-04-25
  • Java Excel导入导出详解

    一、Excel文件简介 Excel是微软公司开发的一种电子表格程序,多用于商业、财务、科学等各种数据处理。 Excel文件通常以.xls或.xlsx格式存储,其中.xls格式为Ex…

    编程 2025-04-25

发表回复

登录后才能评论