赞
踩
1.导包 <!-- https://mvnrepository.com/artifact/org.apache.poi/poi --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.1.2</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.2</version> </dependency>
2.代码
-
- import lombok.extern.slf4j.Slf4j;
- import org.apache.poi.hssf.usermodel.HSSFWorkbook;
- import org.apache.poi.ss.usermodel.*;
- import org.springframework.web.multipart.MultipartFile;
- import org.apache.poi.xssf.usermodel.XSSFWorkbook;
- import java.io.FileNotFoundException;
- import java.io.IOException;
- import java.io.InputStream;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.function.Function;
-
-
- @Slf4j
- public class ExcelAnalysisUtil {
-
- public static <T> List<T> analysis(MultipartFile file, Function<List<String>,T> converter) {
- List<T> row = new ArrayList<>();
- //获取文件名称
- String fileName = file.getOriginalFilename();
-
- try {
- //获取输入流
- InputStream in = file.getInputStream();
- //判断excel版本
- Workbook workbook = null;
- if (judegExcelEdition(fileName)) {
- workbook = new XSSFWorkbook(in);
- } else {
- workbook = new HSSFWorkbook(in);
- }
- //获取第一张工作表
- Sheet sheet = workbook.getSheetAt(0);
- //从第二行开始获取 getLastRowNum
- for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) {
- //循环获取工作表的每一行
- Row sheetRow = sheet.getRow(i);
- //循环获取每一列
- ArrayList<String> cell = new ArrayList<>();
- for (int j = 0; j < sheetRow.getPhysicalNumberOfCells(); j++) {
- //将每一个单元格的值装入列集合
- sheetRow.getCell(j).setCellType(CellType.STRING);
- cell.add(sheetRow.getCell(j).getStringCellValue());
- }
- //将装有每一列的集合装入大集合
- row.add(converter.apply(cell));
-
- //关闭资源
- workbook.close();
- }
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- log.error("===================未找到文件======================");
- } catch (IOException e) {
- e.printStackTrace();
- log.error("===================上传失败======================");
- }
- return row;
- }
-
- /**
- * 获取并解析excel文件,返回一个二维集合
- *
- * @param file 上传的文件
- * @return 二维集合(第一重集合为行,第二重集合为列,每一行包含该行的列集合,列集合包含该行的全部单元格的值)
- */
- public static List<List<String>> analysis(MultipartFile file) {
- return analysis(file,e->e);
- }
-
- /**
- * 判断上传的excel文件版本(xls为2003,xlsx为2017)
- *
- * @param fileName 文件路径
- * @return excel2007及以上版本返回true,excel2007以下版本返回false
- */
- private static boolean judegExcelEdition(String fileName) {
- if (fileName.matches("^.+\\.(?i)(xls)$")) {
- return false;
- } else {
- return true;
- }
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。