admin 管理员组文章数量: 1086866
阿帕奇POI EXCEL解析
阿帕奇POI工具类
package com.llf.util;import com.llf.excel.User;
import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.formula.functions.T;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFFormulaEvaluator;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.joda.time.DateTime;import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;/*** @Author llf* @Date 2022/1/12 15:09* @Version 1.0*/
public class ReadExcelUtil {/*** 根据path后缀 返回不同版本的excel** @param filePath 文件路径* @return* @throws IOException*/public static Workbook suffixChoose(String filePath) throws IOException {Workbook workbook = null;if (filePath == null) {return null;}String extString = filePath.substring(filePath.lastIndexOf("."));FileInputStream stream = null;//后缀类型判断try {stream = new FileInputStream(filePath);if (".xls".equals(extString)) {return new HSSFWorkbook(stream);} else if (".xlsx".equals(extString)) {return new XSSFWorkbook(stream);} else {return null;}} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return workbook;}/*** 通过判断格式 为cell设定java可以表示的格式** @param cell* @return*/public static Object getCellFormatValue(Cell cell,Workbook sheets) {Object cellValue = null;XSSFFormulaEvaluator FormulaEvaluator = new XSSFFormulaEvaluator((XSSFWorkbook) sheets);if (cell != null) {int cellType = cell.getCellType();//判断cell类型switch (cellType) {case HSSFCell.CELL_TYPE_STRING://字符串类型cellValue = cell.getStringCellValue();break;case HSSFCell.CELL_TYPE_BOOLEAN://布尔类型cellValue = String.valueOf(cell.getBooleanCellValue());break;case HSSFCell.CELL_TYPE_BLANK://null 类型break;case HSSFCell.CELL_TYPE_NUMERIC://数字(普通数字、日期)类型if (HSSFDateUtil.isCellDateFormatted(cell)) {Date date = cell.getDateCellValue();cellValue = new DateTime(date).toString("yyyy-MM-dd");} else {//如果不是日期格式 就转换为string类型cell.setCellType(HSSFCell.CELL_TYPE_STRING);cellValue = cell.toString();}break;case HSSFCell.CELL_TYPE_ERROR://数据类型错误break;case HSSFCell.CELL_TYPE_FORMULA://如果是公式String formula = cell.getCellFormula();System.out.println("公式是:"+formula);try {cellValue = String.valueOf(cell.getNumericCellValue());} catch (IllegalStateException e) {cellValue = String.valueOf(cell.getRichStringCellValue());}break;default:cellValue = "";}} else {cellValue = "";}return cellValue;}/*** 通过path解析excel** @param path* @return* @throws IOException*/public static ArrayList<User> ResolveExcelByPath(String path) throws IOException {ArrayList<User> list = new ArrayList<>();//1.得到需要解析的文件Workbook sheets = suffixChoose(path);//2、通过表名称获取工作表对象Sheet sheet = sheets.getSheetAt(0);//获取表的总行数int rowNum = sheet.getPhysicalNumberOfRows();
//总列数int colNum = sheet.getRow(0).getLastCellNum();//获取表头Row row = sheet.getRow(0);if (row != null) {for (int i = 0; i < colNum; i++) {System.out.print(row.getCell(i) + "|");}}System.out.println();
//遍历excel每一行 从1开始 忽略表头for (int j = 1; j <= rowNum; j++) {//拿到每一列的值Row rowData = sheet.getRow(j);if (rowData != null) {Cell cell1 = rowData.getCell(0);
//获取表中第i行,第2列的单元格Cell cell2 = rowData.getCell(1);
//excel表的第i行,第3列的单元格Cell cell3 = rowData.getCell(2);
//excel表的第i行,第4列的单元格 依次类推Cell cell4 = rowData.getCell(3);
//这里new 一个对象,用来装填Excel数据,字段根据excel决定User user = new User();user.setSno((String) ReadExcelUtil.getCellFormatValue(cell1,sheets));user.setName((String) ReadExcelUtil.getCellFormatValue(cell2,sheets));user.setAge((String) ReadExcelUtil.getCellFormatValue(cell3,sheets));user.setBirth((String) ReadExcelUtil.getCellFormatValue(cell4,sheets));list.add(user);}}return list;}
}
这个工具类一共有三个方法suffixChoose
、getCellFormatValue
、ResolveExcelByPath
第一个方法用来判断文件类型是xls还是xlsx 并根据类型创建不同的Workbook对象
第二个方法用来将单元格的值进行识别 并格式化
第三个方法是主启动方法 将文件路径作为参数传入 然后解析
如果使用web页面怎么办
将ResolveExcelByPath
方法的参数 更改成MultipartFile file
使用WorkbookFactory.create
方法 直接将file作为参数转换成流 得到sheets对象
public static ArrayList<User> ResolveExcelByPath(MultipartFile file) throws IOException {// Workbook sheets = suffixChoose(path); 注释掉这个方法即可Workbook sheets = WorkbookFactory.create(file.getInputStream());......}
如果使用Swing界面怎么办?
package com.llf.excel;import com.llf.util.ReadExcelUtil;import javax.swing.*;
import java.io.IOException;
import java.util.ArrayList;/*** @Author llf* @Date 2022/1/12 18:08* @Version 1.0*/
public class test {public static void main(String[] args) throws IOException {String path = null;JFileChooser fc = new JFileChooser();fc.setDialogTitle("文件上传");fc.setApproveButtonText("确定");fc.setFileSelectionMode(JFileChooser.FILES_ONLY);if (JFileChooser.APPROVE_OPTION == fc.showOpenDialog(fc)) {path=fc.getSelectedFile().getPath();System.out.println(path);//这个path 就是excel文件的地址 然后调用 ResolveExcelByPath 方法即可ArrayList<User> list = ReadExcelUtil.ResolveExcelByPath(path);list.forEach(x->{System.out.println(x);});}}}
注意点
采用面向对象的思想 每一张不同表头的表都是一个新的对象,因此在进行解析的时候 就需要使用不用的实体对象来进行存储,因此只需要改动主方法中赋值的代码即可
if (rowData != null) {Cell cell1 = rowData.getCell(0);
//获取表中第i行,第2列的单元格Cell cell2 = rowData.getCell(1);
//excel表的第i行,第3列的单元格Cell cell3 = rowData.getCell(2);
//excel表的第i行,第4列的单元格 依次类推Cell cell4 = rowData.getCell(3);// 有几列 就得到几个cell对象//这里new 一个对象,用来装填Excel数据,字段根据excel决定User user = new User();user.setSno((String) ReadExcelUtil.getCellFormatValue(cell1,sheets));user.setName((String) ReadExcelUtil.getCellFormatValue(cell2,sheets));user.setAge((String) ReadExcelUtil.getCellFormatValue(cell3,sheets));user.setBirth((String) ReadExcelUtil.getCellFormatValue(cell4,sheets));list.add(user);
package com.llf.excel;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;/*** @Author llf* @Date 2022/1/12 14:04* @Version 1.0*/
@AllArgsConstructor
@NoArgsConstructor
@Data
public class User {private String sno;private String name;private String age;private String birth;
}
如果还有不懂的 可以去B站 搜所狂神的poi教程 比较详细
<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></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></dependency><!--文件上传解析--><dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>3.9</version></dependency><!--文件上传解析--><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>3.9</version></dependency><dependency><groupId>joda-time</groupId><artifactId>joda-time</artifactId><version>2.10.10</version></dependency></dependencies>
本文标签: 阿帕奇POI EXCEL解析
版权声明:本文标题:阿帕奇POI EXCEL解析 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.roclinux.cn/b/1693591308a231094.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论