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等工具,输入请求地址和对应的文件,查看控制台打印,和导入的表格内容一致

相关推荐
程序媛小果38 分钟前
基于java+SpringBoot+Vue的宠物咖啡馆平台设计与实现
java·vue.js·spring boot
ruleslol1 小时前
VBA02-初识宏——EXCEL录像机
excel·vba
IT铺子1 小时前
制定Excel使用规范和指导,提升数据处理的效率和准确性,减少错误和数据丢失的风险
excel
是萝卜干呀1 小时前
Backend - Python 爬取网页数据并保存在Excel文件中
python·excel·table·xlwt·爬取网页数据
许野平1 小时前
Rust: 利用 chrono 库实现日期和字符串互相转换
开发语言·后端·rust·字符串·转换·日期·chrono
齐 飞3 小时前
MongoDB笔记01-概念与安装
前端·数据库·笔记·后端·mongodb
狂放不羁霸3 小时前
idea | 搭建 SpringBoot 项目之配置 Maven
spring boot·maven·intellij-idea
LunarCod3 小时前
WorkFlow源码剖析——Communicator之TCPServer(中)
后端·workflow·c/c++·网络框架·源码剖析·高性能高并发
计算机学长felix4 小时前
基于SpringBoot的“校园交友网站”的设计与实现(源码+数据库+文档+PPT)
数据库·spring boot·毕业设计·交友
码农派大星。4 小时前
Spring Boot 配置文件
java·spring boot·后端