700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > Springboot使用Apache POI实现导入导出和解析Excel

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

时间:2020-09-12 20:56:24

相关推荐

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

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

1准备pom文件

<?xml version="1.0" encoding="UTF-8"?><project xmlns="/POM/4.0.0"xmlns:xsi="/2001/XMLSchema-instance"xsi:schemaLocation="/POM/4.0.0 /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 /5/20*/@Controllerpublic 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测试成功

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。