springBoot对接Apache POI 实现excel下载和上传

搭建springboot项目

此处可以参考 搭建最简单的SpringBoot项目_Steven-Russell的博客-CSDN博客

配置Apache POI 依赖

复制代码
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>5.2.2</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>5.2.2</version>
</dependency>

创建controller

复制代码
package com.wd.controller;

import com.wd.utils.ExcelUtils;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping(value = "excel")
public class ExcelController {

    @GetMapping(value = "download")
    public String download(HttpServletResponse httpServletResponse) throws IOException {
        List<String[]> dataList = new ArrayList<>();
        dataList.add(new String[]{"aaa", "add"});
        dataList.add(new String[]{"bbb", "add"});
        dataList.add(new String[]{"ccc", "delete"});
        dataList.add(new String[]{"ddd", "add"});
        dataList.add(new String[]{"eee", "delete"});
        try (SXSSFWorkbook workbook = ExcelUtils.parseInfo2ExcelWorkbook(dataList);
             OutputStream os = httpServletResponse.getOutputStream()){
            httpServletResponse.reset();
            httpServletResponse.setContentType("application/vnd.ms-excel");
            httpServletResponse.setHeader("Content-disposition",
                    "attachment;filename=data_excel_" + System.currentTimeMillis() + ".xlsx");
            workbook.write(os);
            workbook.dispose();
        }

        return "download excel success.";
    }

    @PostMapping(value = "upload")
    public String upload(@RequestParam(value = "file") MultipartFile file) {
        // 获取输入流 注意:SXSSFWorkbook需要关闭流
        try (InputStream inputStream = file.getInputStream();
             XSSFWorkbook workbook = ExcelUtils.parseExcelFile(inputStream)){
            XSSFSheet sheet = workbook.getSheetAt(0);
            for (int i = 0; i < sheet.getLastRowNum(); i++) {
                XSSFRow row = sheet.getRow(i + 1);
                String data = row.getCell(0).getStringCellValue();
                String opr = row.getCell(1).getStringCellValue();
                System.out.println("data : " + data + " <==> " + "opr : " + opr);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return "upload excel failed.";
        }
        return "upload excel success.";
    }

}

创建excel工具类

复制代码
package com.wd.utils;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class ExcelUtils {


    /**
     * 解析数据到excel中
     *
     * @param dataList 数据list信息
     * @return excel对象
     */
    public static SXSSFWorkbook parseInfo2ExcelWorkbook(List<String[]> dataList) {
        SXSSFWorkbook workbook = new SXSSFWorkbook();
        SXSSFSheet sheet = workbook.createSheet("数据");
        // 配置保护当前sheet页不被修改
        sheet.protectSheet("aaa");
        // 此处使用行的变量进行迭代,避免后续行创建出错
        int rows = 0;
        // 表头
        SXSSFRow head = sheet.createRow(rows++);
        CellStyle headCellStyle = createHeadCellStyle(workbook);
        createCell4Head(head, headCellStyle);
        // 表内容填充
        CellStyle bodyCellStyle = createBodyCellStyle(workbook);
        for (String[] dataArr : dataList) {
            SXSSFRow row = sheet.createRow(rows++);;
            createCell4Body(row, bodyCellStyle, dataArr[0], dataArr[1]);
        }
        return workbook;
    }

    private static CellStyle createBodyCellStyle(SXSSFWorkbook workbook) {
        CellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setBorderBottom(BorderStyle.THIN);
        cellStyle.setBorderLeft(BorderStyle.THIN);
        cellStyle.setBorderRight(BorderStyle.THIN);
        cellStyle.setBorderTop(BorderStyle.THIN);
        return cellStyle;
    }

    private static CellStyle createHeadCellStyle(SXSSFWorkbook workbook) {
        CellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setBorderBottom(BorderStyle.THIN);
        cellStyle.setBorderLeft(BorderStyle.THIN);
        cellStyle.setBorderRight(BorderStyle.THIN);
        cellStyle.setBorderTop(BorderStyle.THIN);
        cellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        return cellStyle;
    }

    private static void createCell4Body(SXSSFRow row, CellStyle bodyCellStyle, String data, String opr) {
        SXSSFCell dataCell = row.createCell(0);
        dataCell.setCellStyle(bodyCellStyle);
        dataCell.setCellValue(data);
        SXSSFCell oprCell = row.createCell(1);
        oprCell.setCellStyle(bodyCellStyle);
        oprCell.setCellValue(opr);
    }


    private static void createCell4Head(SXSSFRow head, CellStyle cellStyle) {
        SXSSFCell dataCell = head.createCell(0);
        dataCell.setCellValue("data");
        dataCell.setCellStyle(cellStyle);
        SXSSFCell oprCell = head.createCell(1);
        oprCell.setCellValue("opr");
        oprCell.setCellStyle(cellStyle);
    }

    /**
     * 将输入流封装为 XSSFWorkbook 对象
     *
     * @param inputStream excel 输入流
     * @return XSSFWorkbook 对象
     * @throws IOException 异常信息
     */
    public static XSSFWorkbook parseExcelFile(InputStream inputStream) throws IOException {
        return new XSSFWorkbook(inputStream);
    }
}

启动项目

测试

下载excel

浏览器输入 http://localhost:8888/excel/download

打开下载内容,和代码中的内容进行对比,发现和预期一致

上传excel

打开postman或者Insomnia等工具,输入请求地址和对应的文件,查看控制台打印,和导入的表格内容一致

相关推荐
Mikko737 分钟前
Redis 主从切换期间可用吗?6.2 实测哨兵切换:应用不可写 33 秒,主从连不上、数据不一致,以及设了 ACL 后哨兵不切换
java·运维·redis·后端
猿人谷39 分钟前
从百万个 Pareto 解中选出 100 个:Riesz s-Energy 如何实现高效的多样性选择?
后端·算法·aigc
不积跬步无以至千里mmbb2640 分钟前
【软件工艺师 rust相关课程】
开发语言·后端·rust
不得了zz1 小时前
11-Agent 可观测与评估:Spring AI Alibaba Admin Studio 到底解决了什么
java·人工智能·后端·spring·ai编程·springaialibaba
软件技术NINI1 小时前
基于 SpringBoot 的酒店预定系统
java·spring boot·后端
利威尔xu1 小时前
Go context取消传播3层:信号传不到第3层goroutine,泄漏拖垮
后端·golang
软件技术NINI1 小时前
基于 Spring Boot 中国历史知识学习系统
spring boot·后端·学习
Coder_shen3 小时前
西门子S7-300-400系列PLC-S7comm协议通信驱动的CSharp实现
后端
她的男孩3 小时前
会签选了候选角色,发起却报 nrOfInstances:Forge Admin 改成按人展开集合
spring boot·低代码·工作流引擎
泡海椒3 小时前
Java 生成应急事件地图 PDF:jquick-pdf 地域分布报表的模板逐行解剖
后端