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

news/2024/7/21 5:02:16 标签: spring boot, 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等工具,输入请求地址和对应的文件,查看控制台打印,和导入的表格内容一致


http://www.niftyadmin.cn/n/5017414.html

相关文章

PHP8中获取并删除数组中最后一个元素-PHP8知识详解

在php8中&#xff0c;array_pop()函数将返回数组的最后一个元素&#xff0c;并且将该元素从数组中删除。语法格式如下&#xff1a; array_pop(目标数组) 获取并删除数组中最后一个元素&#xff0c;参考代码&#xff1a; <?php $stu array(s001>明明,s002>亮亮,s…

《C++ primer plus》精炼(OOP部分)——对象和类(2)

“学习是人类成长的喷泉。” - 亚里士多德 文章目录 内联函数对象的方法和属性构造函数和析构函数构造函数的种类使用构造函数析构函数列表初始化 const成员函数this指针对象数组类作用域作用域为类的常量类作用域内的枚举 内联函数 定义位于类声明中的函数自动成为内联函数。…

sqli --【1--10】

Less-1&#xff08;联合查询&#xff09; 1.查看是否有回显 2.查看是否有报错 3.使用联合查询&#xff08;字符注入&#xff09; 3.1判断其列数 3.2 判断显示位置 3.3敏感信息查询 Less-2&#xff08;联合查询&#xff09; 1.查看是否有回显 2.查看是否有报错 3.使用…

基于PyTorch使用LSTM实现新闻文本分类任务

本文参考 PyTorch深度学习项目实战100例 https://weibaohang.blog.csdn.net/article/details/127154284?spm1001.2014.3001.5501 文章目录 本文参考任务介绍做数据的导入 环境介绍导入必要的包介绍torchnet和keras做数据的导入给必要的参数命名加载文本数据数据前处理模型训…

系统架构设计专业技能 · 计算机组成与结构

现在的一切都是为将来的梦想编织翅膀&#xff0c;让梦想在现实中展翅高飞。 Now everything is for the future of dream weaving wings, let the dream fly in reality. 点击进入系列文章目录 系统架构设计高级技能 计算机组成与结构 一、计算机结构1.1 CPU 组成1.2 冯诺依曼…

人工智能TensorFlow PyTorch物体分类和目标检测合集【持续更新】

1. 基于TensorFlow2.3.0的花卉识别 基于TensorFlow2.3.0的花卉识别Android APP设计_基于安卓的花卉识别_lilihewo的博客-CSDN博客 2. 基于TensorFlow2.3.0的垃圾分类 基于TensorFlow2.3.0的垃圾分类Android APP设计_def model_load(img_shape(224, 224, 3)_lilihewo的博客-CS…

使用vcpkg配置CGAL+visual studio 2022

先安装vcpkg C:\dev> git clone https://github.com/microsoft/vcpkg C:\dev> cd vcpkg C:\dev\vcpkg> .\bootstrap-vcpkg.bat 运行后&#xff0c;先执行 C:\dev\vcpkg> .\vcpkg.exe install yasm-tool:x86-windows 这是因为gmp库中有个bug&#xff0c;只能这样…

CSS 文本超出省略

单行省略 width: 200px; /* 容器宽度 */ white-space: nowrap; /* 不换行 */ overflow: hidden; /* 溢出隐藏 */ text-overflow: ellipsis; /* 超出部分省略 */多行省略 display: -webkit-box; -webkit-line-clamp: 2; /* 限制行数 */ -webkit-box-orient: vertical; /* 文本…