Java使用POI导出Excel(二):多个sheet

作者:Javaの甘乃迪 时间:2022-11-26 02:09:44 

相关文章:

Java使用POI导出Excel(一):单sheet

Java使用POI导出Excel(二):多个sheet

相信在大部分的web项目中都会有导出导入Excel的需求,但是在我们日常的工作中,需求往往没这么简单,可能需要将数据按类型分类导出或者数据量过大,需要分多张表导出等等。遇到类似的需求该怎么办呢,别慌,往下看。

一、pom引用

pom文件中,添加以下依赖

<!--Excel工具-->
       <dependency>
           <groupId>org.apache.poi</groupId>
           <artifactId>poi</artifactId>
           <version>5.2.2</version>
           <scope>compile</scope>
       </dependency>
       <dependency>
           <groupId>org.apache.poi</groupId>
           <artifactId>poi-ooxml</artifactId>
           <version>5.2.2</version>
           <scope>compile</scope>
       </dependency>

二、工具类util

1.ExportSheetUtil

 package com.***.excel;

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.springframework.http.MediaType;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;

/**
* @description: excel导出多个sheet工具类
* @author: ***
* @date: 2022/9/15
*/
public class ExportSheetUtil {

/**
    * 拆解并导出多重Excel
    */
   public static void exportManySheetExcel(String fileName, List<ExcelSheet> mysheets, HttpServletResponse response) {
       //创建工作薄
       HSSFWorkbook wb = new HSSFWorkbook();
       //表头样式
       HSSFCellStyle style = wb.createCellStyle();
       // 垂直
       style.setVerticalAlignment(VerticalAlignment.CENTER);
       // 水平
       style.setAlignment(HorizontalAlignment.CENTER);
       //字体样式
       HSSFFont fontStyle = wb.createFont();
       fontStyle.setFontName("微软雅黑");
       fontStyle.setFontHeightInPoints((short) 12);
       style.setFont(fontStyle);
       for (ExcelSheet excel : mysheets) {
           //新建一个sheet
           //获取该sheet名称
           HSSFSheet sheet = wb.createSheet(excel.getFileName());
           //获取sheet的标题名
           String[] handers = excel.getHanders();
           //第一个sheet的第一行为标题
           HSSFRow rowFirst = sheet.createRow(0);
           //写标题
           for (int i = 0; i < handers.length; i++) {
               //获取第一行的每个单元格
               HSSFCell cell = rowFirst.createCell(i);
               //往单元格里写数据
               cell.setCellValue(handers[i]);
               //加样式
               cell.setCellStyle(style);
               //设置每列的列宽
               sheet.setColumnWidth(i, 4000);
           }
           //写数据集
           List<String[]> dataset = excel.getDataset();
           for (int i = 0; i < dataset.size(); i++) {
               //获取该对象
               String[] data = dataset.get(i);
               //创建数据行
               HSSFRow row = sheet.createRow(i + 1);
               for (int j = 0; j < data.length; j++) {
                   //设置对应单元格的值
                   row.createCell(j).setCellValue(data[j]);
               }
           }
       }

// 下载文件谷歌文件名会乱码,用IE
       try {
           response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
           response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName + ".xlsx", "utf-8"));
           response.setHeader("Cache-Control", "No-cache");
           response.flushBuffer();
           wb.write(response.getOutputStream());
           wb.close();
       } catch (Exception e) {
           e.printStackTrace();
       }
   }

}

2.ExcelSheet

 package com.***.excel;

import lombok.Data;

import java.util.List;

/**
* @description: 导出多个sheet表
* @author: ***
* @date: 2022/9/15
*/
@Data
public class ExcelSheet {

/*** sheet的名称*/
   private String fileName;

/*** sheet里的标题*/
   private String[] handers;

/*** sheet里的数据集*/
   private List<String[]> dataset;

public ExcelSheet(String fileName, String[] handers, List<String[]> dataset) {
       this.fileName = fileName;
       this.handers = handers;
       this.dataset = dataset;
   }

}

三、相关业务代码

1.service层

/*** 导出开票及运单信息*/
   ExportInvoiceAndBillVo exportInvoiceAndBillInfo(InvoiceReviewListDto dto);

2.impl实现类

实现类里的代码,需要各位根据自己的业务场景进行改动,无非就是将需要导出的数据先查出来,带入模板中,调用工具类的方法导出。

 package com.***.vo.invoicereview;

import lombok.Data;

import java.io.Serializable;
import java.util.List;

/**
* @description: 导出开票和运单信息Vo
* @author: ***
* @date: 2022/9/19
*/
@Data
public class ExportInvoiceAndBillVo implements Serializable {

/*** 开票信息*/
   private List<String[]> invoiceList;

/*** 运单信息*/
   private List<String[]> billList;

}

     @Override
   public ExportInvoiceAndBillVo exportInvoiceAndBillInfo(InvoiceReviewListDto dto) {
       ExportInvoiceAndBillVo invoiceAndBill = new ExportInvoiceAndBillVo();
       // 查询需要导出的开票信息
       PageInfo<InvoiceReviewListVo> pageInfo = queryInvoiceReviewList(dto);
       List<InvoiceReviewListVo> invoiceList = pageInfo.getList();
       if (invoiceList.size() > 10000) {
           throw new ServiceException("开票数据过多,请分批次导出");
       }
       // 查询需要导出的车运运单信息
       List<Long> invoiceIdList = invoiceList.stream().map(InvoiceReviewListVo::getInvoiceId).collect(Collectors.toList());
       List<ExportBillVo> billList = getBillInfo(invoiceIdList);
       if (billList.size() > 10000) {
           throw new ServiceException("运单数据过多,请分批次导出");
       }
       // 将表1 表2的数据 放入定义的对象Vo中
       invoiceAndBill.setInvoiceList(getInvoiceDataList(invoiceList));
       invoiceAndBill.setBillList(getBillDataList(billList));
       return invoiceAndBill;
   }

3.controller层

controller层的代码需要注意的是:

1.因为导出Excel一般都是通过浏览器进行下载的,所以入参中需要加入HttpServletResponse

2.调用封装的工具类ExportSheetUtil中的exportManySheetExcel方法就可以了

3.表头和表名需要各位根据自身的业务场景修改哈

     /**
    * 导出开票和运单信息
    */
   @Log
   @PostMapping("/exportInvoiceAndBillInfo")
   public void exportInvoiceAndBillInfo(@RequestBody InvoiceReviewListDto dto, HttpServletResponse response) {
       ExportInvoiceAndBillVo invoiceAndBillVo = invoiceFacadeService.exportInvoiceAndBillInfo(dto);
       //设置sheet的表头与表名
       String[] invoiceSheetHead = {"开票编号", "票号", "公司名称", "收票方名称", "结算类型", "纳税识别码", "收票联系人", "联系人电话", "运单总金额(元)", "含税总金额(元)", "开票状态", "提交开票时间", "运营审核时间", "运营审核人", "财务审核时间", "财务审核人", "开票完成时间", "冲销操作人", "冲销时间"};
       String[] billSheetHead = {"开票编号", "运单号", "发货地", "收货地", "司机", "司机电话", "货物名称", "货物数量", "单位", "货物重量(吨)", "运单状态", "运单金额(元)", "含税金额(元)"};
       ExcelSheet invoiceExcel = new ExcelSheet("开票信息", invoiceSheetHead, invoiceAndBillVo.getInvoiceList());
       ExcelSheet billExcel = new ExcelSheet("运单信息", billSheetHead, invoiceAndBillVo.getBillList());
       List<ExcelSheet> mysheet = new ArrayList<>();
       mysheet.add(invoiceExcel);
       mysheet.add(billExcel);
       ExportSheetUtil.exportManySheetExcel("开票及运单信息", mysheet, response);
   }

最终导出的Excel文件:

Java使用POI导出Excel(二):多个sheet

Java使用POI导出Excel(二):多个sheet

来源:https://www.cnblogs.com/wyj-java/p/16747297.html

标签:Java,POI,导出,Excel
0
投稿

猜你喜欢

  • Java手动实现Redis的LRU缓存机制

    2023-07-31 12:51:30
  • Java用栈实现综合计算器

    2021-08-16 02:01:36
  • 你知道在Java中Integer和int的这些区别吗?

    2023-09-04 02:50:18
  • 浅析SpringBoot2.4 静态资源加载问题

    2023-01-29 11:04:33
  • 基于MapReduce实现决策树算法

    2023-10-20 16:05:40
  • Java String源码分析并介绍Sting 为什么不可变

    2021-09-23 06:10:42
  • IDEA快速搭建spring boot项目教程(Spring initializr)

    2023-08-17 21:11:16
  • 详解基于spring多数据源动态调用及其事务处理

    2023-06-23 14:37:25
  • MFC程序设计常用技巧汇总

    2023-11-02 20:37:12
  • Java File类提供的方法与操作

    2023-08-29 09:10:41
  • java线程池对象ThreadPoolExecutor的深入讲解

    2023-05-15 06:49:51
  • springboot返回图片流的实现示例

    2023-11-23 17:30:08
  • 浅谈android Fragment横竖屏翻转对重新加载的要求

    2023-07-27 21:55:28
  • 解决JavaWeb读取本地json文件以及乱码的问题

    2023-09-14 18:35:14
  • Java concurrency线程池之线程池原理(二)_动力节点Java学院整理

    2023-11-28 23:43:18
  • SpringMVC中使用@PathVariable绑定路由中的数组的方法

    2023-11-27 14:21:01
  • Java 单例模式的实现资料整理

    2022-05-29 21:27:33
  • Java设计通用的返回数据格式过程讲解

    2023-11-09 00:16:40
  • 解析springboot整合谷歌开源缓存框架Guava Cache原理

    2023-11-07 13:24:23
  • java中文传值乱码问题的解决方法

    2023-11-25 16:26:47
  • asp之家 软件编程 m.aspxhome.com