java 读取Excel数据(POI)

1、添加依赖


    org.apache.poi
    poi-ooxml
    3.13



    org.apache.poi
    poi-scratchpad
    3.13

2、支持只读一个sheet的工具类

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * POI解析Excel---只读一个sheet
 * 注意:1、若单元格为空时,读出为""空字符串;列数为按最后一列计算;
 * 2、如果在最后一列前单元格合并数据个数还是按合并前列数算,但是合并后单元格只有左上单元格有数据;
 * 3、如果是最后一列合并单元格,则算最前面一列 ,后面列不计算 在其中,也没数据(不是""空串)
 */
public class ExcelReader {

    /**
     * 根据fileType不同读取excel文件
     *
     * @param path
     * @param path
     * @throws IOException
     */
    public static List> readExcel(String path) {
        String fileType = path.substring(path.lastIndexOf(".") + 1);
        // return a list contains many list
        List> lists = new ArrayList>();
        //读取excel文件
        InputStream is = null;
        try {
            is = new FileInputStream(path);
            //获取工作薄
            Workbook wb = null;
            if (fileType.equals("xls")) {
                wb = new HSSFWorkbook(is);
            } else if (fileType.equals("xlsx")) {
                wb = new XSSFWorkbook(is);
            } else {
                return null;
            }

            //读取第一个工作页sheet
            Sheet sheet = wb.getSheetAt(0);
            //第一行为标题
            for (Row row : sheet) {
                ArrayList list = new ArrayList();
                int flag = 0;
                System.out.println(">>>>>>>>>>>"+row.getLastCellNum());
                for (int i = 0; i < row.getLastCellNum(); i++) {
                    Cell cell = row.getCell(i);
                    //根据不同类型转化成字符串
                    //如果单元格是空(列)的跳过-----------合并的单元格值优先属于左上单元格
                    if(cell == null){
                        list.add("");
                    }else if(cell.getCellType() ==3){
                        list.add("");
                    }else if(cell.getCellType() ==0){
                        list.add(handleNumber(String.valueOf(cell.getNumericCellValue())));
                        flag = 1;
                    }else if(cell.getCellType() ==1){
                        cell.setCellType(Cell.CELL_TYPE_STRING);
                        list.add(cell.getStringCellValue());
                        flag = 1;
                    }else {
                        list.add("");
                    }
                }
                //如果整行都没有值,跳过整行
                if(list.size() != 0 && flag == 1){
                    lists.add(list);
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return lists;
    }

    /**
     *  去掉数字字符串小数点后面无效的领,或者去掉小数点
     * 

Description : * @param number String * @return java.lang.String *

Date: 2019/11/14 11:17
Author : dxl */ public static String handleNumber(String number){ if(number.contains(".") && number.substring(number.indexOf(".")+1,number.length()).length() == 16){ if(number.substring(number.length()-1,number.length()).equals("1")){ number = number.substring(0,number.length()-1); }else if(number.substring(number.length()-1,number.length()).equals("9")){ Double tem = Double.valueOf(number) + 0.0000000000000002; number = tem.toString(); } } if(!number.contains(".")){ return number; }else if(number.lastIndexOf(".") == number.length()-1){ number = number.substring(0,number.length()-1); return number; }else if(number.substring(number.length()-1,number.length()).equals("0")){ number = number.substring(0,number.length()-1); number = handleNumber(number); }else { return number; } return number; } /** * 创建Excel.xls * @param lists 需要写入xls的数据 * @param titles 列标题 * @param name 文件名 * @return * @throws IOException */ public static Workbook creatExcel(List> lists, String[] titles, String name) throws IOException { System.out.println(lists); //创建新的工作薄 Workbook wb = new HSSFWorkbook(); // 创建第一个sheet(页),并命名 Sheet sheet = wb.createSheet(name); // 手动设置列宽。第一个参数表示要为第几列设;,第二个参数表示列的宽度,n为列高的像素数。 for(int i=0;i>>>ii>>>>"+ii); String path = "D:/111.xls"; List> lists = readExcel(path); for (List list : lists) { System.out.println(">>"+list); System.out.println("--------------------------"); for (String strs : list) { System.out.println(strs); } } } }

3、支持多个sheet数据读取工具类

import org.apache.poi.hssf.usermodel.*;
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.*;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 读取Excel数据工具类----可以读取多个sheet
 *  注意:1、若单元格为空时,读出为""空字符串;列数为按最后一列计算;
 * 2、如果在最后一列前单元格合并数据个数还是按合并前列数算,但是合并后单元格只有左上单元格有数据;
 * 3、如果是最后一列合并单元格,则算最前面一列 ,后面列不计算 在其中,也没数据(不是""空串)
 * @time 2017-06-03
 */
public class ExcelReaderPlus {
    private static HSSFWorkbook wb;
    private static HSSFSheet sheet;
    private static HSSFRow row;
    private static XSSFWorkbook wbx;
    private static XSSFSheet sheetx;
    private static XSSFRow rowx;

    /**
     * 获取多个sheetExcel表格数据
     * 注意:1、若单元格为空时,读出为""空字符串;列数为按最后一列计算;
     * 2、如果在最后一列前单元格合并还是数据个数还是按合并前列数算,但是合并后单元格只有左上单元格有数据;
     * 3、如果是最后一列合并单元格,则算最前面一列 ,后面列不计算 在其中,也没数据(不是""空串)
     * @param filePath Excel路径
     * @return
     */
    public ExcelData readExcel(String filePath) {
        InputStream is = null;
        File file = new File(filePath);
        try {
            is = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        ExcelData excelData = new ExcelData();
        try {
            if(filePath.substring(filePath.length()-5,filePath.length()).equals(".xlsx")){
                wbx = new XSSFWorkbook(is);
               return readExcelx(wbx,file.getName());
            }
            wb = new HSSFWorkbook(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Integer sheetNum = wb.getNumberOfSheets();
        excelData.setSheetSum(sheetNum);
        excelData.setFileName(file.getName());

        //循环获取所有sheet数据
        List sheetDatas = new ArrayList<>();
        for (int i = 0; i < sheetNum; i++) {
            ExcelSheetData sheetData = new ExcelSheetData();
            sheet = wb.getSheetAt(i);
            sheetData.setLineSum(sheet.getPhysicalNumberOfRows());
            sheetData.setSheetName(sheet.getSheetName());

            List lineDatas = readExcelContentBySheet(sheet);
            sheetData.setLineData(lineDatas);
            sheetDatas.add(sheetData);
        }
        excelData.setSheetData(sheetDatas);
        return excelData;
    }

    private ExcelData readExcelx(XSSFWorkbook wbx,String fileName) {

        ExcelData excelData = new ExcelData();
        Integer sheetNum = wbx.getNumberOfSheets();
        excelData.setSheetSum(sheetNum);
        excelData.setFileName(fileName);

        //循环获取所有sheet数据
        List sheetDatas = new ArrayList<>();
        for (int i = 0; i < sheetNum; i++) {
            ExcelSheetData sheetData = new ExcelSheetData();
            sheetx = wbx.getSheetAt(i);
            sheetData.setSheetName(sheetx.getSheetName());
            sheetData.setLineSum(sheetx.getPhysicalNumberOfRows());
            List lineDatas = readExcelContentBySheetx(sheetx);
            sheetData.setLineData(lineDatas);
            sheetDatas.add(sheetData);
        }
        excelData.setSheetData(sheetDatas);
        return excelData;
    }



    private List readExcelContentBySheet(HSSFSheet sheet) {
        List lineDatas = new ArrayList<>();
        // 得到总行数
        int rowNum = sheet.getLastRowNum();
        for (int i = 0; i <= rowNum; i++) {
            int j = 0;
            row = sheet.getRow(i);
            if (Objects.isNull(row)) {
                continue;
            }

            int colNum = row.getLastCellNum();
            ExcelLineData lineData = new ExcelLineData();
            List colData = new ArrayList<>();
            lineData.setColSum(colNum);
            while (j < colNum) {
                String value = getCellValue(row.getCell(j)).trim();
                colData.add(value);
                j++;
            }
            lineData.setColData(colData);
            lineDatas.add(lineData);
        }

        return lineDatas;
    }
    private List readExcelContentBySheetx(XSSFSheet sheetx) {
        List lineDatas = new ArrayList<>();
        // 得到总行数
        int rowNum = sheetx.getLastRowNum();
        for (int i = 0; i <= rowNum; i++) {
            int j = 0;
            rowx = sheetx.getRow(i);
            if (Objects.isNull(rowx)) {
                continue;
            }

            int colNum = rowx.getLastCellNum();
            ExcelLineData lineData = new ExcelLineData();
            List colData = new ArrayList<>();
            lineData.setColSum(colNum);
            while (j < colNum) {
                String value = getCellValuex(rowx.getCell(j)).trim();
                colData.add(value);
                j++;
            }
            lineData.setColData(colData);
            lineDatas.add(lineData);
        }

        return lineDatas;
    }

    /**
     * 获取单元格数据
     *
     * @param cell Excel单元格
     * @return String 单元格数据内容
     */
    private String getCellValue(HSSFCell cell) {
        if (Objects.isNull(cell)) {
            return "";
        }

        String value = "";
        switch (cell.getCellType()) {
            case HSSFCell.CELL_TYPE_NUMERIC: // 数字
                //如果为时间格式的内容
                if (HSSFDateUtil.isCellDateFormatted(cell)) {
                    //注:format格式 yyyy-MM-dd hh:mm:ss 中小时为12小时制,若要24小时制,则把小h变为H即可,yyyy-MM-dd HH:mm:ss
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                    value = sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue())).toString();
                    break;
                } else {
                    value = new DecimalFormat("0").format(cell.getNumericCellValue());
                }
                break;
            case HSSFCell.CELL_TYPE_STRING: // 字符串
                value = cell.getStringCellValue();
                break;
            case HSSFCell.CELL_TYPE_BOOLEAN: // Boolean
                value = cell.getBooleanCellValue() + "";
                break;
            case HSSFCell.CELL_TYPE_FORMULA: // 公式
                value = cell.getCellFormula() + "";
                break;
            case HSSFCell.CELL_TYPE_BLANK: // 空值
                value = "";
                break;
            case HSSFCell.CELL_TYPE_ERROR: // 故障
                value = "非法字符";
                break;
            default:
                value = "未知类型";
                break;
        }
        return value;
    }

    private String getCellValuex(XSSFCell cellx) {
        if (Objects.isNull(cellx)) {
            return "";
        }

        String value = "";
        switch (cellx.getCellType()) {
            case XSSFCell.CELL_TYPE_NUMERIC: // 数字
                //如果为时间格式的内容
                if (HSSFDateUtil.isCellDateFormatted(cellx)) {
                    //注:format格式 yyyy-MM-dd hh:mm:ss 中小时为12小时制,若要24小时制,则把小h变为H即可,yyyy-MM-dd HH:mm:ss
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                    value = sdf.format(HSSFDateUtil.getJavaDate(cellx.getNumericCellValue())).toString();
                    break;
                } else {
                    value = new DecimalFormat("0").format(cellx.getNumericCellValue());
                }
                break;
            case XSSFCell.CELL_TYPE_STRING: // 字符串
                value = cellx.getStringCellValue();
                break;
            case XSSFCell.CELL_TYPE_BOOLEAN: // Boolean
                value = cellx.getBooleanCellValue() + "";
                break;
            case XSSFCell.CELL_TYPE_FORMULA: // 公式
                value = cellx.getCellFormula() + "";
                break;
            case XSSFCell.CELL_TYPE_BLANK: // 空值
                value = "";
                break;
            case XSSFCell.CELL_TYPE_ERROR: // 故障
                value = "非法字符";
                break;
            default:
                value = "未知类型";
                break;
        }
        return value;
    }


    public static void main(String[] args) {
        ExcelReaderPlus excelReader = new ExcelReaderPlus();
        ExcelData excelData = excelReader.readExcel("D:\\111.xls");
        System.out.println(excelData.toString());
        for(ExcelSheetData excelSheetData:excelData.getSheetData()){
            System.out.println("**********************"+excelSheetData.getSheetName());
            for(ExcelLineData excelLineData :excelSheetData.getLineData()){
                System.out.println("----------------"+excelLineData.getColSum());
                System.out.println(">>>>>>>"+excelLineData.getColData());
            }
        }

    }


    public class ExcelData {
        private int sheetSum;
        private String fileName;
        private List sheetData;

        public int getSheetSum() {
            return sheetSum;
        }

        public void setSheetSum(int sheetSum) {
            this.sheetSum = sheetSum;
        }

        public String getFileName() {
            return fileName;
        }

        public void setFileName(String fileName) {
            this.fileName = fileName;
        }

        public List getSheetData() {
            return sheetData;
        }

        public void setSheetData(List sheetData) {
            this.sheetData = sheetData;
        }
    }

    public class ExcelSheetData {
        /**
         * 工作簿名称
         */
        private String sheetName;
        /**
         * 表格总行数
         */
        private int lineSum;
        /**
         * 行数据集合
         */
        private List lineData;

        public String getSheetName() {
            return sheetName;
        }

        public void setSheetName(String sheetName) {
            this.sheetName = sheetName;
        }

        public int getLineSum() {
            return lineSum;
        }

        public void setLineSum(int lineSum) {
            this.lineSum = lineSum;
        }

        public List getLineData() {
            return lineData;
        }

        public void setLineData(List lineData) {
            this.lineData = lineData;
        }
    }
    public class ExcelLineData {
        /**
         * 行编号
         */
        private int lineNumber;
        /**
         * 行总列数
         */
        private int colSum;
        /**
         * 列数据集合
         */
        private List colData;

        public int getLineNumber() {
            return lineNumber;
        }

        public void setLineNumber(int lineNumber) {
            this.lineNumber = lineNumber;
        }

        public int getColSum() {
            return colSum;
        }

        public void setColSum(int colSum) {
            this.colSum = colSum;
        }

        public List getColData() {
            return colData;
        }

        public void setColData(List colData) {
            this.colData = colData;
        }
    }

}

 

你可能感兴趣的:(java-Excel,java工具类)