java的Excel导出方式总结

本文详细介绍了如何使用Hutool、EasyExcel和EasyPoi库在Java中导出Excel。从简单的表头导出到包含内容和下拉列表的复杂场景,每个步骤都有清晰的代码示例。此外,还提到了项目资源文件导出Excel的问题及其解决方案,以及在pom.xml中的配置注意事项。
摘要由CSDN通过智能技术生成

一、使用hutool导出excel

   1.1 hutool介绍

        hutool功能很强大,http请求到json处理、excel的导入导出、定时任务、IO、缓存、数据库操作等都提供了简单而方便的api供我们使用,好处是再也不用担心自己去整理常用的工具类了,同时也支持按需引入【但一般项目都是直接一如hutool-all 导致项目引入很多不必要的工具类】。

       从2014年首次发布第一版本到现在已经8年了,这款国产工具类确实收获了越来越多的关注,而且社区的热度是可以的,但是比起Apache或者谷歌提供的工具类,更新频率和可靠性也许稍差,但在我看来是可以考虑使用的。

   1.2 编写代码导出excel【仅表头】

 我们要的效果:

     

 所需编写的代码:

    @GetMapping("/exportTemplate")
    public void exportTemplate(HttpServletResponse response) throws IOException {
        String column1Name1 = "时间戳";
        String column1Name2 = "设备名称";

        List<String> headList = new ArrayList<>();
        headList.add(column1Name1);
        headList.add(column1Name2);

        //在内存操作,写到浏览器
        ExcelWriter writer= ExcelUtil.getWriter(true);

        // 设置表头的宽度
        writer.setColumnWidth(0, 20);
        writer.setColumnWidth(1, 15);

        writer.writeHeadRow(headList).write(Collections.emptyList());
        //设置content—type
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset:utf-8");

        //Content-disposition是MIME协议的扩展,MIME协议指示MIME用户代理如何显示附加的文件。
        response.setHeader("Content-Disposition","attachment;filename="+URLEncoder.encode("数据集导入模板","UTF-8")+".xlsx");
        ServletOutputStream outputStream= response.getOutputStream();

        //将Writer刷新到OutPut
        writer.flush(outputStream,true);
        outputStream.close();
        writer.close();
    }

1.3 编写代码导出excel【含内容】

    

 我们要的效果:

     

 所需编写的代码:

    @GetMapping("/exportTemplate")
    public void exportTemplate(HttpServletResponse response) throws IOException {
        String column1Name1 = "时间戳";
        String column1Name2 = "设备名称";

        List<String> headList = new ArrayList<>();
        headList.add(column1Name1);
        headList.add(column1Name2);

        //在内存操作,写到浏览器
        ExcelWriter writer= ExcelUtil.getWriter(true);

        // 设置表头的宽度
        writer.setColumnWidth(0, 20);
        writer.addHeaderAlias("timestamp",column1Name1);
        writer.setColumnWidth(1, 15);
        writer.addHeaderAlias("deviceName",column1Name2);

        // 默认的,未添加alias的属性也会写出,如果想只写出加了别名的字段,可以调用此方法排除之
        writer.setOnlyAlias(true);

        // 表格内容【相比上一节新内容】
        List<CollectDataExcelVo> excelList = new ArrayList<>();
        CollectDataExcelVo vo1 = new CollectDataExcelVo();
        vo1.setDeviceName("A类设备");
        vo1.setTimestamp(DateUtil.format(new Date()));
        excelList.add(vo1);
        CollectDataExcelVo vo2 = new CollectDataExcelVo();
        vo2.setDeviceName("B类设备");
        vo2.setTimestamp(DateUtil.format(new Date()));
        excelList.add(vo2);

        writer.writeHeadRow(headList).write(excelList);
        //设置content—type
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset:utf-8");

        //Content-disposition是MIME协议的扩展,MIME协议指示MIME用户代理如何显示附加的文件。
        response.setHeader("Content-Disposition","attachment;filename="+URLEncoder.encode("数据集导入模板","UTF-8")+".xlsx");
        ServletOutputStream outputStream= response.getOutputStream();

        //将Writer刷新到OutPut
        writer.flush(outputStream,true);
        outputStream.close();
        writer.close();
    }
@Data
public class CollectDataExcelVo {
    /**
     * 时间戳
     */
    @ApiModelProperty(value = "时间戳")
    private String timestamp;
    /**
     * 设备编码
     */
    @ApiModelProperty(value = "设备名称")
    private String deviceName;
}

 1.4 编写代码导出excel【导出下拉列表】

 我们要的效果:

     

 所需编写的代码:

    @GetMapping("/exportTemplate")
    public void exportTemplate(HttpServletResponse response) throws IOException {
        String column1Name1 = "时间戳";
        String column1Name2 = "设备名称";

        List<String> headList = new ArrayList<>();
        headList.add(column1Name1);
        headList.add(column1Name2);

        //在内存操作,写到浏览器
        ExcelWriter writer= ExcelUtil.getWriter(true);

        // 设置表头的宽度
        writer.setColumnWidth(0, 20);
        writer.addHeaderAlias("timestamp",column1Name1);
        writer.setColumnWidth(1, 15);
        writer.addHeaderAlias("deviceName",column1Name2);

        // 默认的,未添加alias的属性也会写出,如果想只写出加了别名的字段,可以调用此方法排除之
        writer.setOnlyAlias(true);

        // 表格下拉框【相比上一节新内容】
        writer.addSelect(1, 1, new String[]{"1#进线","2#进线", "3#进线"});
        writer.writeHeadRow(headList).write(Collections.emptyList());

        //设置content—type
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset:utf-8");

        //Content-disposition是MIME协议的扩展,MIME协议指示MIME用户代理如何显示附加的文件。
        response.setHeader("Content-Disposition","attachment;filename="+URLEncoder.encode("数据集导入模板","UTF-8")+".xlsx");
        ServletOutputStream outputStream= response.getOutputStream();

        //将Writer刷新到OutPut
        writer.flush(outputStream,true);
        outputStream.close();
        writer.close();
    }

二、使用easyexcel导出excel

2.1 easyexcel介绍

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

   2.2 编写代码导出excel

 我们要的效果:

  

 所需编写的代码:

pom引入依赖:

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>3.0.5</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.1.2</version>
        </dependency> 

java代码:

import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.write.style.ColumnWidth;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

@Data
public class CollectDataExcelVo {
    /**
     * 时间戳
     */
    @ExcelProperty(value = "时间戳", index = 0)
    @ColumnWidth(value = 20)
    @ApiModelProperty(value = "时间戳")
    private String timestamp;
    /**
     * 设备名称
     */
    @ExcelProperty(value = "设备名称", index = 1)
    @ColumnWidth(value = 15)
    @ApiModelProperty(value = "设备名称")
    private String deviceName;
}
    @GetMapping("/exportTemplate")
    public void exportTemplate(HttpServletResponse response) throws IOException {
        // 模拟数据库获取数据
        List<CollectDataExcelVo> list = data();

        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.setHeader("content-Type", "application/vnd.ms-excel");
        response.setHeader("Content-Disposition",
                "attachment;filename=" + URLEncoder.encode("template"+ DateUtils.format(new Date(), "yyyy-MM-dd")+".xlsx", StandardCharsets.UTF_8.name()));

        EasyExcel.write(response.getOutputStream(), CollectDataExcelVo.class).sheet().doWrite(list);
    }

    private List<CollectDataExcelVo> data() {
        List<CollectDataExcelVo> list = ListUtils.newArrayList();
        for (int i = 1; i <= 2; i++) {
            CollectDataExcelVo data = new CollectDataExcelVo();
            data.setTimestamp(DateUtil.format(new Date()));
            data.setDeviceName("A类设备"+i);
            list.add(data);
        }
        return list;
    }

三、从项目resources目录导出excel

3.1 将文件放入项目路径下

       

3.2 将文件导出

      将文件从项目工程的 resources/file 目录下导出,所需代码如下:

import org.apache.poi.util.IOUtils;

    @GetMapping("/exportTemplate")
    public void exportTemplate(HttpServletResponse response) {

        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            String fileName= URLEncoder.encode("template","UTF-8");
            outputStream = response.getOutputStream();
            // 获取springboot resource 路径下的文件
            inputStream = this.getClass().getResourceAsStream("/file/template.xlsx");
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition","attachment;filename="+fileName+".xlsx");
            IOUtils.copy(inputStream, outputStream);

        } catch (Exception e) {
            throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, e.toString());
        } finally {
            closeInput(inputStream);
            flushOutput(outputStream);

        }
    }

    private void flushOutput(OutputStream outputStream) {
        try {
            outputStream.flush();
        } catch (IOException e) {
            logger.error("释放流异常", e);
        }
    }

    private void closeInput(InputStream inputStream) {
        try {
            inputStream.close();
        } catch (IOException e) {
            logger.error("释放流异常", e);
        }
    }

   导出后会存在问题 excel文件导出后打不开!! 只需再pom.xml中配置如下即可:

    <plugins>
        <!-- maven资源文件复制插件 -->
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-resources-plugin</artifactId>
            <configuration>
                <encoding>UTF-8</encoding>
                <nonFilteredFileExtensions>
                    <nonFilteredFileExtension>xls</nonFilteredFileExtension>
                    <nonFilteredFileExtension>xlsx</nonFilteredFileExtension>
                </nonFilteredFileExtensions>
            </configuration>
        </plugin>
    </plugins>

四、使用easypoi 导出excel

4.1 easypoi 介绍

        easypoi 也是国产开源的软件,它通过简单的注解和模板语言 (熟悉的表达式语法),就可以实现excel的导入导出功能。

   4.2 编写代码导出excel

 我们要的效果:

  

 所需编写的代码:

pom引入依赖:

        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-base</artifactId>
            <version>4.1.0</version>
        </dependency>
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-web</artifactId>
            <version>4.1.0</version>
        </dependency>
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-annotation</artifactId>
            <version>4.1.0</version>
        </dependency>

java代码:

// 工具类
public class ExcelUtil {

    public static void exportExcel(List<?> list, Class<?> pojoClass, String fileName, boolean isCreateHeader, HttpServletResponse response) {
        ExportParams exportParams = new ExportParams();
        exportParams.setCreateHeadRows(isCreateHeader);
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
        if (workbook != null) ;
        try {
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            try {
                throw new Exception(e.getMessage());
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    }

}
import cn.afterturn.easypoi.excel.annotation.Excel;
import lombok.Data;
import java.util.Date;

@Data
public class CollectDataExcelVo {
    /**
     * 时间戳
     */
    @Excel(name = "时间戳",format="yyyy-MM-dd HH:mm:ss", width = 20.0)
    private Date timestamp;
    /**
     * 设备编码
     */
    @Excel(name = "设备名称", width = 20)
    private String deviceName;
}

    @GetMapping("/export")
    @ApiOperation("导出数据")
    public void export(HttpServletResponse response) {
        String fileName = "template"+".xls";
        List<CollectDataExcelVo> list = data();
        ExcelUtil.exportExcel(list, CollectDataExcelVo.class, fileName, true, response);
    }

============

以上就是博主的excel导出方式总结,如有问题 欢迎在评论区留言

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值