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

本文涉及的产品
公共DNS(含HTTPDNS解析),每月1000万次HTTP解析
云解析 DNS,旗舰版 1个月
云解析DNS,个人版 1个月
简介: 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方法

首先先用


image


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


image


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


image

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测试成功

相关文章
|
29天前
|
缓存 监控 架构师
价值32k!阿里顶级架构师深度解析SpringBoot进阶原理实战手册
在当下的互联网应用中,业务体系日益复杂,业务功能也在不断地变化。以典型的电商类应用为例,其背后的业务功能复杂度以及快速迭代要求的开发速度,与5年前的同类业务系统相比,面临着诸多新的挑战。这些挑战中核心的一点就是快速高效地实现系统功能,同时保证代码持续可维护,这是一个非常现实且亟待解决的问题。
|
3月前
|
XML Java 应用服务中间件
深度解析SpringBoot内嵌Web容器
今天分享一个SpringBoot的内嵌Web容器,在SpringBoot还没有出现时,我们使用Java开发了Web项目,需要将其部署到Tomcat下面,需要配置很多xml文件,SpringBoot出现后,就从繁琐的xml文件中解脱出来了,SpringBoot将Web容器进行了内嵌,我们只需要将项目打成一个jar包,就可以运行了,大大省略了开发成本,那么SpringBoot是怎么实现的呢,我们今天就来详细介绍。
114 2
|
4月前
|
XML 存储 Java
SpringBoot结合POI实现百万级数据报表操作
SpringBoot结合POI实现百万级数据报表操作
53 0
|
4月前
|
XML Java BI
SpringBoot实现POI报表操作
SpringBoot实现POI报表操作
56 0
|
4月前
|
前端开发 Java 数据库
SpringBoot解析指定Yaml配置文件
最近在看某个开源项目代码并准备参与其中,代码过了一遍后发现多个自定义的配置文件用来装载业务配置代替数据库查询,直接响应给前端,这里简单记录一下实现过程。
142 0
|
5月前
|
消息中间件 安全 NoSQL
跪了!Alibaba内部优质Springboot笔记:两大项目实战+源码解析
近年来,Spring Boot 是整个Java社区中最有影响力的项目之一,它的设计初衷是解决Spring各版本配置工作过于繁重,目前已经逐渐替代传统SSM架构。但SSM和Spring Boot并不冲突。Spring Boot更简单、更自动化,减少了传统SSM开发的配置。程序员在用Springboot开发应用程序时能做到零配置或极简配置。同时,为了不失灵活性,它也支持自定义操作。
|
5月前
|
Java Spring 容器
SpringBoot启动原理——Run方法源码解析《课时十二》
SpringBoot启动原理——Run方法源码解析《课时十二》
56 0
|
5月前
|
前端开发 Java 应用服务中间件
SpringBoot自动配置原理:解析Pom.xml文件《第五课》
SpringBoot自动配置原理:解析Pom.xml文件《第五课》
53 0
|
5月前
|
JSON 缓存 安全
SpringBoot 配置CORS处理前后端分离跨域配置无效问题解析
SpringBoot 配置CORS处理前后端分离跨域配置无效问题解析
|
6月前
|
Java 容器 Spring
Springboot源码:自动装配流程解析
Springboot源码:自动装配流程解析
42 0
热门文章
最新文章
相关产品
云迁移中心
推荐文章
更多
推荐镜像
更多