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

本文涉及的产品
云解析 DNS,旗舰版 1个月
全局流量管理 GTM,标准版 1个月
公共DNS(含HTTPDNS解析),每月1000万次HTTP解析
简介: 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测试成功

相关文章
|
5月前
|
存储 缓存 算法
分布式锁服务深度解析:以Apache Flink的Checkpointing机制为例
【10月更文挑战第7天】在分布式系统中,多个进程或节点可能需要同时访问和操作共享资源。为了确保数据的一致性和系统的稳定性,我们需要一种机制来协调这些进程或节点的访问,避免并发冲突和竞态条件。分布式锁服务正是为此而生的一种解决方案。它通过在网络环境中实现锁机制,确保同一时间只有一个进程或节点能够访问和操作共享资源。
199 3
|
6月前
|
安全 网络协议 应用服务中间件
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的重要桥梁,扮演着至关重要的角色
179 2
|
4月前
|
消息中间件 Java Kafka
什么是Apache Kafka?如何将其与Spring Boot集成?
什么是Apache Kafka?如何将其与Spring Boot集成?
159 5
|
4月前
|
消息中间件 Java Kafka
Spring Boot 与 Apache Kafka 集成详解:构建高效消息驱动应用
Spring Boot 与 Apache Kafka 集成详解:构建高效消息驱动应用
105 1
|
4月前
|
消息中间件 存储 负载均衡
Apache Kafka核心概念解析:生产者、消费者与Broker
【10月更文挑战第24天】在数字化转型的大潮中,数据的实时处理能力成为了企业竞争力的重要组成部分。Apache Kafka 作为一款高性能的消息队列系统,在这一领域占据了重要地位。通过使用 Kafka,企业可以构建出高效的数据管道,实现数据的快速传输和处理。今天,我将从个人的角度出发,深入解析 Kafka 的三大核心组件——生产者、消费者与 Broker,希望能够帮助大家建立起对 Kafka 内部机制的基本理解。
148 2
|
5月前
|
Java Apache
Apache POI java对excel表格进行操作(读、写) 有代码!!!
文章提供了使用Apache POI库在Java中创建和读取Excel文件的详细代码示例,包括写入数据到Excel和从Excel读取数据的方法。
409 0
|
6月前
|
分布式计算 Java Apache
Apache Spark Streaming技术深度解析
【9月更文挑战第4天】Apache Spark Streaming是Apache Spark生态系统中用于处理实时数据流的一个重要组件。它将输入数据分成小批次(micro-batch),然后利用Spark的批处理引擎进行处理,从而结合了批处理和流处理的优点。这种处理方式使得Spark Streaming既能够保持高吞吐量,又能够处理实时数据流。
109 0
|
10天前
|
算法 测试技术 C语言
深入理解HTTP/2:nghttp2库源码解析及客户端实现示例
通过解析nghttp2库的源码和实现一个简单的HTTP/2客户端示例,本文详细介绍了HTTP/2的关键特性和nghttp2的核心实现。了解这些内容可以帮助开发者更好地理解HTTP/2协议,提高Web应用的性能和用户体验。对于实际开发中的应用,可以根据需要进一步优化和扩展代码,以满足具体需求。
58 29
|
7天前
|
前端开发 数据安全/隐私保护 CDN
二次元聚合短视频解析去水印系统源码
二次元聚合短视频解析去水印系统源码
27 3
|
9天前
|
JavaScript 算法 前端开发
JS数组操作方法全景图,全网最全构建完整知识网络!js数组操作方法全集(实现筛选转换、随机排序洗牌算法、复杂数据处理统计等情景详解,附大量源码和易错点解析)
这些方法提供了对数组的全面操作,包括搜索、遍历、转换和聚合等。通过分为原地操作方法、非原地操作方法和其他方法便于您理解和记忆,并熟悉他们各自的使用方法与使用范围。详细的案例与进阶使用,方便您理解数组操作的底层原理。链式调用的几个案例,让您玩转数组操作。 只有锻炼思维才能可持续地解决问题,只有思维才是真正值得学习和分享的核心要素。如果这篇博客能给您带来一点帮助,麻烦您点个赞支持一下,还可以收藏起来以备不时之需,有疑问和错误欢迎在评论区指出~

推荐镜像

更多