Java中 POI读取Excel工具类

直接上代码

pom文件需要导入这些依赖

org.apache.poi
poi-ooxml
3.9


org.apache.poi
poi-ooxml-schemas
3.9


org.apache.poi
poi
3.9



org.apache.poi
poi
3.10-FINAL
jar
compile


org.apache.poi
poi-ooxml
3.10-FINAL
jar


org.apache.poi
poi-ooxml-schemas
3.10-FINAL
jar
compile


org.apache.poi
poi-scratchpad
3.10-FINAL
jar
compile

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
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.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

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

public class ReadExcel {

    //读取excel表标头数据
    public static List<String> readTitleExcel(String path) {
        String fileType = path.substring(path.lastIndexOf(".") + 1);
        // return a list contains many list
        List<List<String>> lists = new ArrayList<List<String>>();
        //读取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<String> list = new ArrayList<String>();
                for (Cell cell : row) {
                    //根据不同类型转化成字符串
                    cell.setCellType(Cell.CELL_TYPE_STRING);
                    list.add(cell.getStringCellValue());
                }
                lists.add(list);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) {is.close();}
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        List<String> list = lists.get(0);

        return list;
    }

    //报错的时候走这个接口
    public static String readXlsxCount(String path) {
        List<List<String>> list = new ArrayList<>();
        String fileType = path.substring(path.lastIndexOf(".") + 1);
        // return a list contains many list
        //读取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);
            //获取总行数
            int rowTotalCount = sheet.getLastRowNum();
            //获取标题的总行数
            int columnCount = sheet.getRow(0).getPhysicalNumberOfCells();

            String count = rowTotalCount+"-"+columnCount ;
            System.out.println("行数为:"+rowTotalCount+"列数为:"+columnCount);

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

    //xls和xlsx都可以使用(除标头,不包括第一行)
    public static List<List<String>> readXlsxExcel(String path) {
        List<List<String>> list = new ArrayList<>();
        String fileType = path.substring(path.lastIndexOf(".") + 1);
        // return a list contains many list
        //读取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);
            //获取总行数
            int rowTotalCount = sheet.getLastRowNum();
            //获取标题的总行数
            int columnCount = sheet.getRow(0).getPhysicalNumberOfCells();

            System.out.println("行数为:"+rowTotalCount+"列数为:"+columnCount);
            if (fileType.equals("xlsx")) {
                for (int i = 1; i <= rowTotalCount; i++) {
                    ArrayList<String> listRow = new ArrayList<String>();
                    // 获取第i列的row对象
                    XSSFRow row = (XSSFRow) sheet.getRow(i);
                    for (int j = 0; j < columnCount; j++) {
                        //下列步骤为判断cell读取到的数据是否为null 如果不做处理 程序会报错
                        String cell = null;
                        //如果未null则加上""组装成非null的字符串
                        if (row.getCell(j) == null) {
                            listRow.add("");
                            //如果读取到cell不为null 则直接加入	listRow集合
                        } else {
                            cell = row.getCell(j).toString();
                            listRow.add(cell);
                        }
                        // 在第i列 依次获取第i列的第j个位置上的值 %15s表示前后间隔15个字节输出
                    }
                    list.add(listRow);
                }
            }else {
                for (int i = 1; i <= rowTotalCount; i++) {
                    ArrayList<String> listRow = new ArrayList<String>();
                    // 获取第i列的row对象
                    HSSFRow row = (HSSFRow) sheet.getRow(i);
                    for (int j = 0; j < columnCount; j++) {
                        //下列步骤为判断cell读取到的数据是否为null 如果不做处理 程序会报错
                        String cell = null;
                        //如果未null则加上""组装成非null的字符串
                        if (row.getCell(j) == null) {
                            listRow.add("");
                            //如果读取到cell不为null 则直接加入	listRow集合
                        } else {
                            cell = row.getCell(j).toString();
                            listRow.add(cell);
                        }
                        // 在第i列 依次获取第i列的第j个位置上的值 %15s表示前后间隔15个字节输出
                    }
                    list.add(listRow);
                }
            }
            return list;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) {is.close();}
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return list;
    }

    //只能适用于xls
    public static List<List<String>> ReadExcel(String filePath){
        List<List> list = new ArrayList<>();
        try {
            // 建需要读取的excel文件写入stream
            HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(filePath));
            // 指向sheet下标为0的sheet 即第一个sheet 也可以按在sheet的名称来寻找
            HSSFSheet sheet = workbook.getSheetAt(0);
            // 获取sheet1中的总行数
            int rowTotalCount = sheet.getLastRowNum();
            //获取总列数
            int columnCount = sheet.getRow(0).getPhysicalNumberOfCells();

            System.out.println("行数为:"+rowTotalCount+"列数为:"+columnCount);
            for (int i = 0; i <= rowTotalCount; i++) {
                // 获取第i列的row对象
                HSSFRow row = sheet.getRow(i);

                ArrayList<String> listRow = new ArrayList<String>();
                for (int j = 0; j < columnCount; j++) {
                    //下列步骤为判断cell读取到的数据是否为null 如果不做处理 程序会报错
                    String cell = null;
                    //如果未null则加上""组装成非null的字符串
                    if(row.getCell(j) == null){

                        cell = row.getCell(j)+"";

                        listRow.add(cell);
                        //如果读取到cell不为null 则直接加入	listRow集合
                    }else{
                        cell = row.getCell(j).toString();
                        listRow.add(cell);
                    }
                    // 在第i列 依次获取第i列的第j个位置上的值 %15s表示前后间隔15个字节输出
                }
                list.add(listRow);
            }
            List<List<String>> listList = new ArrayList<>();
            for (int i=1;i<list.size();i++){
                listList.add(list.get(i));
            }
            return listList;
        } catch (FileNotFoundException e) {

            e.printStackTrace();
        } catch (IOException e) {

            e.printStackTrace();
        }

        return null;
    }

    //读取管线表
    public static List<List<String>> readLineExcel(String path) {
        List<List<String>> list = new ArrayList<>();
        String fileType = path.substring(path.lastIndexOf(".") + 1);
        // return a list contains many list
        //读取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);
            //获取总行数
            int rowTotalCount = sheet.getLastRowNum();
            //获取标题的总行数
            int columnCount = sheet.getRow(0).getPhysicalNumberOfCells();
            System.out.println("行数为:"+rowTotalCount+"列数为:"+columnCount);
            if (columnCount != 20){
                return null;
            }
            if (fileType.equals("xlsx")) {
                for (int i = 3; i <= rowTotalCount; i++) {
                    ArrayList<String> listRow = new ArrayList<String>();
                    // 获取第i列的row对象
                    XSSFRow row = (XSSFRow) sheet.getRow(i);
                    for (int j = 0; j < columnCount; j++) {
                        //下列步骤为判断cell读取到的数据是否为null 如果不做处理 程序会报错
                        String cell = null;
                        //如果未null则加上""组装成非null的字符串
                        if (row.getCell(j) == null) {

                            cell = row.getCell(j) + "";

                            listRow.add("");
                            //如果读取到cell不为null 则直接加入	listRow集合
                        } else {
                            cell = row.getCell(j).toString();
                            listRow.add(cell);
                        }
                        // 在第i列 依次获取第i列的第j个位置上的值 %15s表示前后间隔15个字节输出
                    }
                    list.add(listRow);
                }
            }else {
                for (int i = 3; i <= rowTotalCount; i++) {
                    ArrayList<String> listRow = new ArrayList<String>();

                    // 获取第i列的row对象

                    HSSFRow row = (HSSFRow) sheet.getRow(i);
                    for (int j = 0; j < columnCount; j++) {
                        //下列步骤为判断cell读取到的数据是否为null 如果不做处理 程序会报错
                        String cell = null;
                        //如果未null则加上""组装成非null的字符串
                        if (row.getCell(j) == null) {

                            cell = row.getCell(j) + "";

                            listRow.add("");
                            //如果读取到cell不为null 则直接加入	listRow集合
                        } else {
                            cell = row.getCell(j).toString();
                            listRow.add(cell);
                        }
                        // 在第i列 依次获取第i列的第j个位置上的值 %15s表示前后间隔15个字节输出
                    }
                    list.add(listRow);
                }
            }
            return list;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return list;
    }
}

接口:

 /**
     * 缓冲区
     */
    @PostMapping("/test")
    @ApiOperation("test")
    public R test(){
        String path = "C:\\Users\\70490\\Documents\\WeChat Files\\wxid_yxfik7e0yef322\\FileStorage\\File\\2020-08\\410000河南省收购站信息.xlsx";
        List<List<String>> lists = ReadExcel.readXlsxExcel(path);
        List<RanchEntity> entityList = new ArrayList<>();
        for (List<String> list : lists) {
            RanchEntity entity = new RanchEntity();
            entity.setRanchId(list.get(1));
            entity.setRanchName(list.get(2));
            entity.setRanchAddress(list.get(3));
            entity.setAreaCode(list.get(10));
            entity.setAreaName(list.get(7)+list.get(9)+list.get(11));
            entity.setMobile(list.get(6));
            entity.setXCoordinate(new BigDecimal(list.get(14).split(",")[0]));
            entity.setYCoordinate(new BigDecimal(list.get(14).split(",")[1]));
            ranchService.save(entity);
        }
        return R.ok();
    }

RanchEntity是实体 ,将Excel表格中的数据导入到数据库表中,list就是导入的表 下标是excel中的列 从零开始,想赋值给哪一个字段就选择对应的下标

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值