ExcelUtils.java 1.83 KB
package com.gelvshi.utils;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.ss.usermodel.Cell;
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;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;

public class ExcelUtils {

    //处理excel表格的工具类
    public static List<Object[]> readXls(File upload) throws Exception{
        FileInputStream is = new FileInputStream(upload);
        Workbook wb = new XSSFWorkbook(is);
        Sheet sheet = wb.getSheetAt(0);
        //创建工作簿对应的表头
        List<Object[]> strList = new ArrayList<>();
        //看这张表总共有多少行
        int lastRowNum = sheet.getLastRowNum();
        try{
            for (int i = 0;i<=lastRowNum;i++){
                //读取到某一行
                Row row = sheet.getRow(i);
                //看总共有多少列
                short lastCellnum = row.getLastCellNum();
                //从第0个索引开始
                Object[] rowData = new Object[lastCellnum];
                for (int j = 0;j<lastCellnum;j++){
                    //拿到行其中的格子
                    Cell cell = row.getCell(j);
                    if(cell.getCellType()== HSSFCell.CELL_TYPE_STRING){
                        rowData[j] = cell.getStringCellValue();
                    }else if(cell.getCellType()== HSSFCell.CELL_TYPE_NUMERIC){
                        rowData[j] = cell.getNumericCellValue();
                    }

                }
                strList.add(rowData);
            }
            //读取数据
            return strList;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
}