package com.baiyz.utils;  

import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Map;

/**
* <p> * Description: 读取Excel工具类
* </p >
* <p>PackageName: com.baiyz.utils</p > * <p>ClassName: ReadExcelUtils</p > * * @author <a href="mail to: byz0825@outlook.com" rel="nofollow">BaiYZ</a >
* @since 2022-09-16 10:09:38
*/@Slf4j
public class ReadExcelUtils {

/**
* 读取Excel工具类
* @param path 文件路径
* @param sheetName 表格名称
* @return 表格全部数据 LinkedList<Map<String, String>>
* @throws FileNotFoundException 未找到文件异常
*/
private LinkedList<Map<String, String>> getExcel(String path, String sheetName) throws FileNotFoundException {
LinkedList<Map<String, String>> ans = null;
try(FileInputStream inputStream = new FileInputStream(new File(path))){
//存储整个结果
ans = new LinkedList<>();
XSSFWorkbook sheets = new XSSFWorkbook(inputStream);
XSSFSheet sheet = sheets.getSheet(sheetName);
//处理不存在sheet
if (sheet == null){
return new LinkedList<>();
} XSSFRow titleRow = sheet.getRow(0);
for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) {
//存储一行结果
LinkedHashMap<String, String> rowData = new LinkedHashMap<>();
XSSFRow row = sheet.getRow(i);
//读取格数
for (int j = 0; j < row.getPhysicalNumberOfCells(); j++) {
XSSFCell cell = row.getCell(j);
XSSFCell titleCell = titleRow.getCell(j);
cell.setCellType(CellType.STRING);
if(cell.getStringCellValue() .equals("")){
continue;
} rowData.put(getString(titleCell),getString(cell));
} ans.add(rowData);
}
}catch (Exception e){
log.info("读取文件出现异常:"+e);
} return ans;
} /**
* 把单元格的内容转为字符串
*
* @param xssfCell 单元格
* @return String
*/ private static String getString(XSSFCell xssfCell) {
if (xssfCell == null) {
return "";
} if (xssfCell.getCellType() == CellType.NUMERIC) {
return String.valueOf(xssfCell.getNumericCellValue());
} else if (xssfCell.getCellType() == CellType.BOOLEAN) {
return String.valueOf(xssfCell.getBooleanCellValue());
} else {
return xssfCell.getStringCellValue();
} }}