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><!-- <!– mybatis-spring-boot-starter –>-->
<!-- <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")@ResponseBodypublic 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")@ResponseBodypublic 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();// 解析并且封装到一个listList<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++) {// 每一行数据对应一个mapMap<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);// 设置类型为Stringcell.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测试成功
Springboot使用Apache POI实现导入导出和解析Excel相关推荐
- JAVA语言(POI数据导入导出Excel)
POI数据导入导出Excel(样式可以自己设置) //----------------------------Controller层 --------------------------------- ...
- POI动态字段导出Excel-导入Excel,解析加密数据再导出
一.POI动态字段导出Excel-导入Excel 1.直接导出Excel public static void main(String[] args) throws IOException { // ...
- linux读取excel并导入mysql_mysql命令行的导入导出sql,txt,excel(都在linux或windows命令行操作)(转自筑梦悠然)...
Mysql导入导出sql,txt,excel 首先我们通过命令行进入到mysql安装目录的bin目录下,比如我输入的命令行为: d: cd D:/wamp/bin/mysql/mysql5.6.17 ...
- C#导入导出数据到Excel的通用类源码
下面内容是关于C#导入导出数据到Excel的通用类的内容. public class ExcelIO { private int _ReturnStatus; private string _Retu ...
- CATIA批量导入导出数据到EXCEL
CATIA批量导入导出数据到EXCEL 序言 一.EXCEL数据点批量导入到CATIA 二.CATIA数据点批量导入到EXCEL 三.VB批量输出点到EXCEL 序言 工作中,由于测量基准和建模基准不 ...
- poi/jxls导入/导出Excel工具类(支持2003和2007)
1.ExportUtil导出工具类(根据模板导出),支持2003/2007不同excel格式文件 package org.nercita.bcp.util;import java.io.FileInp ...
- springboot集成easyExcel实现文件导入导出
EasyExcel简介 EasyExcel是一个基于Java的简单.省内存的读写Excel的开源项目.在尽可能节约内存的情况下支持读写百M的Excel. EasyExcel使用 导入依赖 <de ...
- POI实现导入导出excel
poi在日常的导入导出中是比较常用到的,最近也总结了下接触到的poi相关的导入导出的一些代码,有问题可以指出: package com.poi;import km.org.apache.poi.hss ...
- java excel 导入导出_java中excel文件的导入和导出
如有需要可以加我Q群[308742428]大家一起讨论技术,提供技术支持. 后面会不定时为大家更新文章,敬请期待. 前端上传excel文件到后台,后台接收后保存数据到数据库. 这里需要说明的一点是前端 ...
最新文章
- html 中如何写js代码提示错误,javascript怎么进行错误处理?
- 学习JS的心路历程-参数传递方式(上)
- 微信小程序——真机调试方法(vConsole)
- 内存池和tcmalloc的性能比较
- jenkins maven testng selenium自动化持续集成
- 使用HTTPS和OAuth 2.0保护服务到服务的Spring微服务
- linux切换到字符界面stemctl,CentOS7两种模式
- 用Python采集了几千条相亲文案,终于发现了告别单身的秘密
- UL/OL与LI 标签结合CSS的运用
- 梅林系统软件无法安装解决方法
- 怎么利用电脑摄像头和上传图片读取扫描二维码内容
- Nginx企业级配置
- CSDN - CSDN27题解
- 若依框架图片上传、富文本框编辑器功能
- 提高代码质量——使用Jest和Sinon给已有的代码添加单元测试
- 域名解析协议-DNS
- C语言 投票系统:给定候选人,从键盘输入候选人的名字,统计票数,并输出最终获胜者...
- MATLAB/simulink学习笔记(二)——对正弦函数判断的正负以及分段函数仿真
- mysql校验日期是否有效_Mysql 根据出生日期计算年龄 判断起始日期是否在某个有效时间段内等日期Hack汇总...
- php7 css样式不支持,div错位/解决IE6、IE7、IE8样式不兼容问题_html/css_WEB-ITnose