Springboot使用Apache POI实现导入导出和解析Excel

简介: Springboot使用Apache POI实现导入导出和解析Excel

前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到网站点击跳转浏览。


1准备pom文件


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.miyo</groupId>
    <artifactId>miyo-file-server</artifactId>
    <version>1.0-SNAPSHOT</version>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.8</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--热部署配置-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>
<!--        &lt;!&ndash; mybatis-spring-boot-starter &ndash;&gt;-->
<!--        <dependency>-->
<!--            <groupId>org.mybatis.spring.boot</groupId>-->
<!--            <artifactId>mybatis-spring-boot-starter</artifactId>-->
<!--            <version>2.1.1</version>-->
<!--        </dependency>-->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.4</version>
        </dependency>
<!--        <dependency>-->
<!--            <groupId>mysql</groupId>-->
<!--            <artifactId>mysql-connector-java</artifactId>-->
<!--            <scope>runtime</scope>-->
<!--        </dependency>-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

2 在controller里面有生成Excel,解析Excel方法

首先先用



这个方法,导出一个Excel,然后将文件放到



这个位置之后就可以根据前端传来的数值进行修改模板中字段了。


package com.miyo.controller;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Font;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;
/**
 * @author xiaoli.he
 * @date 2022/5/20
 */
@Controller
public class TemplateController {
  /**
   * 根据模板修改下载对应的Excel
   *
   * @param response excel
   * @param templateCode code
   * @param includeFields 选中的字段
   * @throws Exception null
   */
  @SuppressWarnings("resource")
  @RequestMapping("/download")
  @ResponseBody
  public void download(
      HttpServletResponse response, String templateCode, @RequestBody List<String> includeFields)
      throws Exception {
    // 测试
    int length = templateCode.length();
    System.out.println(length);
    // 判断得到那些值
    // 模板文件放在resources中的download包中
    String filePath =
        Objects.requireNonNull(TemplateController.class.getClassLoader().getResource("download"))
                .getPath()
            + "/template.xls";
    FileInputStream fileInputStream = new FileInputStream(filePath);
    BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
    POIFSFileSystem fileSystem = new POIFSFileSystem(bufferedInputStream);
    HSSFWorkbook workbook = new HSSFWorkbook(fileSystem);
    HSSFSheet sheet = workbook.getSheet("Sheet1");
    // 得到第一行
    HSSFRow row = sheet.getRow(0);
    // 得到最后一列
    short lastCellNum = row.getLastCellNum();
    // 判断那些列需要采用
    for (int j = 0; j < lastCellNum; j++) {
      String cellValue = row.getCell(j).getStringCellValue();
      HSSFCell cell = row.getCell(j);
      // 没有则从模板中移除
      if (!includeFields.contains(cellValue)) {
        row.removeCell(cell);
      }
    }
    bufferedInputStream.close();
    // 输出Excel文件
    OutputStream outputStream = response.getOutputStream();
    response.reset();
    response.setContentType("application/vnd.ms-excel");
    response.setHeader("Content-disposition", "attachment;filename=template.xls");
    workbook.write(outputStream);
    outputStream.flush();
    outputStream.close();
  }
  /**
   * 解析Excel
   *
   * @param file file
   * @throws Exception null
   */
  @SuppressWarnings("resource")
  @RequestMapping("/parse")
  @ResponseBody
  public void parse(@RequestParam("file") MultipartFile file) throws Exception {
    InputStream inputStream = file.getInputStream();
    BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
    POIFSFileSystem fileSystem = new POIFSFileSystem(bufferedInputStream);
    HSSFWorkbook workbook = new HSSFWorkbook(fileSystem);
    HSSFSheet sheet = workbook.getSheetAt(0);
    // 得到行数
    int lastRowNum = sheet.getLastRowNum();
    // 解析并且封装到一个list
    List<Map<String, String>> listMaps = new ArrayList<>();
    // 得到第一行作为表头
    HSSFRow row1 = sheet.getRow(0);
    int lastCellNum = row1.getLastCellNum();
    String[] arr = new String[lastCellNum];
    // 存入数组中
    for (int t = 0; t < lastCellNum; t++) {
      HSSFCell cell = row1.getCell(t);
      String cellValue = cell.getStringCellValue();
      arr[t] = cellValue;
    }
    for (int i = 1; i <= lastRowNum; i++) {
      // 每一行数据对应一个map
      Map<String, String> map = new HashMap<>(16);
      HSSFRow row = sheet.getRow(i);
      // 得到有几列
      int num = row.getLastCellNum();
      // 遍历每一行的单元格
      for (int j = 0; j < num; j++) {
        HSSFCell cell = row.getCell(j);
        // 设置类型为String
        cell.setCellType(org.apache.poi.ss.usermodel.Cell.CELL_TYPE_STRING);
        String cellValue = cell.getStringCellValue();
        // 把表头和里面的值对应
        map.put(arr[j], cellValue);
      }
      listMaps.add(map);
    }
    System.out.println(listMaps);
  }
  /**
   * 生成Excel
   *
   * @param response Excel
   * @throws Exception null
   */
  @SuppressWarnings("resource")
  @RequestMapping("/exportExcel")
  public void exportExcel(HttpServletResponse response) throws Exception {
    // 创建一个excel的文档对象
    HSSFWorkbook workbook = new HSSFWorkbook();
    // 创建excel的表单
    HSSFSheet sheet = workbook.createSheet("Sheet1");
    // cell样式
    HSSFCellStyle cellStyle = workbook.createCellStyle();
    // 设置水平和垂直居中
    cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
    cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
    // 生成一个字体
    Font font = workbook.createFont();
    font.setFontHeightInPoints((short) 9);
    // 设置字体的颜色
    font.setColor(HSSFColor.BLUE.index);
    // 设置字体加粗
    font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
    cellStyle.setFont(font);
    // 创建一个行
    HSSFRow row = sheet.createRow(0);
    // 设计表头
    String[] tableHeaders = {
      "公司", "毛利率", "净现比", "管理费用率", "销售费用率", "预付账款周转率", "应收账款周转率", "应付账款周转率", "其他应收款占总资产比", "其他应付应收比"
    };
    // 创建表头
    for (int i = 0; i < tableHeaders.length; i++) {
      // 如果用了添加表头
      // 创建单元格并设置单元格内容
      HSSFCell cell = row.createCell(i);
      // 表头数组
      cell.setCellValue(tableHeaders[i]);
      // 赋予格式
      cell.setCellStyle(cellStyle);
    }
    // 输出Excel文件
    OutputStream outputStream = response.getOutputStream();
    response.reset();
    response.setContentType("application/vnd.ms-excel");
    response.setHeader("Content-disposition", "attachment;filename=template.xls");
    workbook.write(outputStream);
    outputStream.flush();
    outputStream.close();
  }
}

3,之后用postman测试成功

相关文章
|
3月前
|
数据挖掘 数据库 Python
Django实战:基于Django和openpyxl实现Excel导入导出功能
`openpyxl` 是用于处理 Excel 文件的 Python 库。本文详解其在 Django 项目中的实战应用,涵盖 Excel 文件的生成、下载、上传与解析。
108 0
Django实战:基于Django和openpyxl实现Excel导入导出功能
|
6月前
|
存储 SQL 缓存
Apache Doris & SelectDB 技术能力全面解析
本文将对 Doris & SelectDB 适合的分析场景和技术能力进行概述解析
889 1
Apache Doris & SelectDB 技术能力全面解析
|
12月前
|
存储 缓存 算法
分布式锁服务深度解析:以Apache Flink的Checkpointing机制为例
【10月更文挑战第7天】在分布式系统中,多个进程或节点可能需要同时访问和操作共享资源。为了确保数据的一致性和系统的稳定性,我们需要一种机制来协调这些进程或节点的访问,避免并发冲突和竞态条件。分布式锁服务正是为此而生的一种解决方案。它通过在网络环境中实现锁机制,确保同一时间只有一个进程或节点能够访问和操作共享资源。
408 3
|
安全 网络协议 应用服务中间件
AJP Connector:深入解析及在Apache HTTP Server中的应用
【9月更文挑战第6天】在Java Web应用开发中,Tomcat作为广泛使用的Servlet容器,经常与Apache HTTP Server结合使用,以提供高效、稳定的Web服务。而AJP Connector(Apache JServ Protocol Connector)作为连接Tomcat和Apache HTTP Server的重要桥梁,扮演着至关重要的角色
357 2
|
11月前
|
消息中间件 Java Kafka
什么是Apache Kafka?如何将其与Spring Boot集成?
什么是Apache Kafka?如何将其与Spring Boot集成?
550 5
|
11月前
|
消息中间件 Java Kafka
Spring Boot 与 Apache Kafka 集成详解:构建高效消息驱动应用
Spring Boot 与 Apache Kafka 集成详解:构建高效消息驱动应用
320 1
|
11月前
|
消息中间件 存储 负载均衡
Apache Kafka核心概念解析:生产者、消费者与Broker
【10月更文挑战第24天】在数字化转型的大潮中,数据的实时处理能力成为了企业竞争力的重要组成部分。Apache Kafka 作为一款高性能的消息队列系统,在这一领域占据了重要地位。通过使用 Kafka,企业可以构建出高效的数据管道,实现数据的快速传输和处理。今天,我将从个人的角度出发,深入解析 Kafka 的三大核心组件——生产者、消费者与 Broker,希望能够帮助大家建立起对 Kafka 内部机制的基本理解。
326 2
|
12月前
|
Java Apache
Apache POI java对excel表格进行操作(读、写) 有代码!!!
文章提供了使用Apache POI库在Java中创建和读取Excel文件的详细代码示例,包括写入数据到Excel和从Excel读取数据的方法。
1392 0
|
21天前
|
人工智能 运维 Java
Flink Agents:基于Apache Flink的事件驱动AI智能体框架
本文基于Apache Flink PMC成员宋辛童在Community Over Code Asia 2025的演讲,深入解析Flink Agents项目的技术背景、架构设计与应用场景。该项目聚焦事件驱动型AI智能体,结合Flink的实时处理能力,推动AI在工业场景中的工程化落地,涵盖智能运维、直播分析等典型应用,展现其在AI发展第四层次——智能体AI中的重要意义。
316 27
Flink Agents:基于Apache Flink的事件驱动AI智能体框架
|
10月前
|
存储 人工智能 大数据
The Past, Present and Future of Apache Flink
本文整理自阿里云开源大数据负责人王峰(莫问)在 Flink Forward Asia 2024 上海站主论坛开场的分享,今年正值 Flink 开源项目诞生的第 10 周年,借此时机,王峰回顾了 Flink 在过去 10 年的发展历程以及 Flink社区当前最新的技术成果,最后展望下一个十年 Flink 路向何方。
684 33
The Past, Present and Future of Apache Flink

推荐镜像

更多