java解析动态Excel

核心

1、判断当前Excel类型,xls或xlsx,然后读取内容

public static Workbook readExcel(String filePath){
        Workbook wb = null;
        if(filePath==null){
            return null;
        }
        String extString = filePath.substring(filePath.lastIndexOf("."));
        InputStream is = null;
        try {
            is = new FileInputStream(filePath);
            if(".xls".equals(extString)){
                return wb = new HSSFWorkbook(is);
            }else if(".xlsx".equals(extString)){
                return wb = new XSSFWorkbook(is);
            }else{
                return wb = null;
            }
            
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return wb;
    }

2、获取当前Excel中sheet页,获取当前sheet页的行数,获取当前行的列数

wb.getNumberOfSheets()可获得Excel总sheet页
sheet.getPhysicalNumberOfRows() 获取当前sheet页行数
row.getPhysicalNumberOfCells() 获取当前行列数

3、建立二维数组,遍历Excel保存数据到二维数组。

通过步骤2中的方法计算出行和列之后,可以新建一个二维数组,用于保存当前sheet页的行和列数据。如果sheet页是动态,那么可以考虑使用三维数组,但三维数组可能一部分人纠结在sheet页下标放在x还是z,个人觉的x,行和列可以往后移动。

使用 二维数组可以这么初始化

String columns[][] = new String[rownum][colnum];
        			for (int i = 1; i < rownum; i++) {
        				row = sheet.getRow(i);
        				if(row !=null){
        					for (int j = 0;j < colnum;j++){
        						try {
        							cellData = (String) getCellFormatValue(row.getCell(j));
        							columns[i][j] = cellData;
        						} catch (Exception e) {
        							
        							e.printStackTrace();
        						}
        					}
        				}
        			}

如使用三维数组可直接初始化三维数组

String columns[][][] = new String[wb.getNumberOfSheets()][rownum][colnum];

sheet页我们已经做了处理,所以可以直接用获取sheet的方法遍历即可,以下一致。

注意单元格类型判断和内容获取时的重复和顺序以及异常处理情况

public static Object getCellFormatValue(Cell cell) throws Exception{
        Object cellValue = null;
        if(cell!=null){
            //判断cell类型
            switch(cell.getCellType()){
            case Cell.CELL_TYPE_NUMERIC:
            	if (DateUtil.isCellDateFormatted(cell)) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    try {
                        cellValue = sdf.format(cell.getDateCellValue());// 日期
                    } catch (Exception e) {
                        throw new Exception("exception on get date data !".concat(e.toString()));
                    }finally{
                        sdf = null;
                    }
                } else {
                    BigDecimal bd = new BigDecimal(cell.getNumericCellValue()); 
                    cellValue = bd.toPlainString();// 数值 这种用BigDecimal包装再获取plainString,可以防止获取到科学计数值
                }
            case Cell.CELL_TYPE_FORMULA:
                //判断cell是否为日期格式
                if(DateUtil.isCellDateFormatted(cell)){
                    //转换为日期格式YYYY-mm-dd
                    cellValue = cell.getDateCellValue();
                }else{
                    //数字
                    cellValue = String.valueOf(cell.getNumericCellValue());
                }
                break;
            
            case Cell.CELL_TYPE_STRING:
                cellValue = cell.getRichStringCellValue().getString();
                break;
                
            case Cell.CELL_TYPE_BLANK:
                cellValue = "";
                break;
            case Cell.CELL_TYPE_BOOLEAN:
                cellValue = String.valueOf(cell.getBooleanCellValue());
                
            case Cell.CELL_TYPE_ERROR: // 故障
                cellValue = "ERROR";
                
            default:
                cellValue = "N/A";
            }
        }else{
            cellValue = "";
        }
        return cellValue;
    }

main方法:

for (int n = 0; n <wb.getNumberOfSheets(); n++) {
        		//获取第一个sheet
        		sheet = wb.getSheetAt(n);
        		//获取最大行数
        		int rownum = sheet.getPhysicalNumberOfRows();
        		if(rownum > 0) {
        			//获取第一行
        			row = sheet.getRow(0);
        			//获取最大列数
        			int colnum = row.getPhysicalNumberOfCells();
        			String columns[][] = new String[rownum][colnum];
        			for (int i = 1; i < rownum; i++) {
        				row = sheet.getRow(i);
        				if(row !=null){
        					for (int j = 0;j < colnum;j++){
        						try {
        							cellData = (String) getCellFormatValue(row.getCell(j));
        							columns[i][j] = cellData;
        						} catch (Exception e) {
        							
        							e.printStackTrace();
        						}
        					}
        				}
        			}
        			list.add(columns);
        		}
			}

导入的poi使用的jar包

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章