【Apache POI】Excel操作(五):Excel数据的读取

不管什么样的人,或者说不管人在什么样的境况下,都可以活得多么好啊!

前言

本文最后一个章节 <往期回顾> 中的系列博客已经给大家讲解了一系列的Excel写入操作,本篇博客将给大家带来Apache POI对Excel的读取操作!!!

读取准备

所需依赖

本文所需的依赖如下:

	<!-- xls(03) -->
	<dependency>
		<groupId>org.apache.poi</groupId>
		<artifactId>poi</artifactId>
		<version>3.9</version>
	</dependency>
	
	<!-- xlsx(07) -->
	<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.1</version>
	</dependency>

	 <!-- 测试 -->
     <dependency>
         <groupId>junit</groupId>
         <artifactId>junit</artifactId>
         <version>4.12</version>
     </dependency>

excel文件生成

我们用代码来生成一下用以读取的excel文件

先自定义一个路径:

	/**
     * 路径
     */
    String PATH = "D:\\IdeaProjects\\my_study_demo\\src\\main\\java\\excel\\read";

再自定义一个文件名:

	/**
     * 文件名
     */
    String FILENAME = "古阙月的读值示范表03.xls";

再来一个方法生成含有不同数据类型的excel文件:

/**
     * 生成一张excel03版本的读值示范表
     * @throws Exception
     */
    @Test
    public void write03Test() throws Exception {

        // 创建一张工作簿
        Workbook workbook = new HSSFWorkbook();
        // 创建一张工作表
        Sheet sheet1 = workbook.createSheet("读值示范");

        /**
         * 创建第一行
         */
        Row row1 = sheet1.createRow(0);
        // 创建第一行第一列
        Cell cell11 = row1.createCell(0);
        // 填值
        cell11.setCellValue("字符串类型");

        // 创建第一行第二列
        Cell cell12 = row1.createCell(1);
        // 填值
        cell12.setCellValue("布尔类型");

        // 创建第一行第三列
        Cell cell13 = row1.createCell(2);
        // 填值
        cell13.setCellValue("空");

        // 创建第一行第四列
        Cell cell14 = row1.createCell(3);
        // 填值
        cell14.setCellValue("数字");

        // 创建第一行第五列
        Cell cell15 = row1.createCell(4);
        // 填值
        cell15.setCellValue("日期");


        /**
         * 创建第二行
         */
        Row row2 = sheet1.createRow(1);
        // 创建第二行第一列
        Cell cell21 = row2.createCell(0);
        // 填值
        cell21.setCellValue("字符串");

        // 创建第二行第二列
        Cell cell22 = row2.createCell(1);
        // 填值
        cell22.setCellValue(true);

        // 创建第二行第三列
        Cell cell23 = row2.createCell(2);
        // 填值
        cell23.setCellValue("");

        // 创建第二行第四列
        Cell cell24 = row2.createCell(3);
        // 填值
        cell24.setCellValue(666666666);

        // 创建第二行第五列
        Cell cell25 = row2.createCell(4);
        // 填值
        cell25.setCellValue(new DateTime().toString("yyyy-MM-dd HH:mm:ss"));

        // 用IO流生成一张Excel表(03版本)- 后缀.xls
        FileOutputStream fileOutputStream = new FileOutputStream(PATH + File.separator + FILENAME);
        // 写入
        workbook.write(fileOutputStream);
        // 关流
        fileOutputStream.close();

        System.out.println(FILENAME + "生成完毕!!!");
    }

运行方法,控制台输出:
在这里插入图片描述
根据之前的定义的路径PATH找到生成的excel文件:
在这里插入图片描述

开始读取

话不多说,直接上代码,解释都在代码注释里。如有不懂的地方,也欢迎找我探讨:

	/**
     * excel03版本读取测试
     */
    @Test
    public void readExcel03Test() throws Exception {

        FileInputStream fileInputStream = new FileInputStream(PATH + File.separator + FILENAME);
        // 获取Excel工作簿
        Workbook workbook = new HSSFWorkbook(fileInputStream);
        if (workbook != null) {

            // 获取第一个工作表
            Sheet sheet = workbook.getSheetAt(0);
            if (sheet != null) {

                /**
                 * 获取标题部分
                 */
                Row rowTitle = sheet.getRow(0); // 获取第一行 - 即标题行
                if (rowTitle != null) {

                    int cellTitles = rowTitle.getPhysicalNumberOfCells(); // 获取第一行的列数
                    for (int i = 0; i < cellTitles; i++) {

                        Cell cell = rowTitle.getCell(i); // 获取对应的列
                        if (cell != null) {
                            System.out.print(cell.getStringCellValue() + " | ");
                        }
                    }
                    System.out.println("\n======================================="); // 换行
                }

                /**
                 * 获取内容部分
                 */
                int rows = sheet.getPhysicalNumberOfRows(); // 获取所有的行数
                for (int i = 1; i < rows; i++) {

                    Row row = sheet.getRow(i); // 获取对应的行
                    if (row != null) {
                        int cells = row.getPhysicalNumberOfCells(); // 获取所有的列数

                        for (int j = 0; j < cells; j++) {
                            // 打印一下 行-列 号
                            System.out.print("[" + i + "-" + j + "]");

                            Cell cell = row.getCell(j); // 获取对应的列
                            if (cell != null) {
                                int cellType = cell.getCellType();
                                Object value = "";

                                switch (cellType) {
                                    case HSSFCell.CELL_TYPE_STRING: // 字符串类型
                                        value = cell.getStringCellValue();
                                        break;
                                    case HSSFCell.CELL_TYPE_BLANK: // 空
                                        break;
                                    case HSSFCell.CELL_TYPE_BOOLEAN: // 布尔类型
                                        value = cell.getBooleanCellValue();
                                        break;
                                    case HSSFCell.CELL_TYPE_NUMERIC: // 数字
                                        if (HSSFDateUtil.isCellDateFormatted(cell)) { // 日期
                                            Date date = cell.getDateCellValue();
                                            value = new DateTime(date).toString("yyyy-MM-dd HH:mm:ss");
                                        }else { // 普通数字
                                            // 转成字符串,以防止过长无法显示
                                            cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                                            value = cell;
//                                            value = cell.getNumericCellValue();
                                        }
                                        break;
                                    case HSSFCell.CELL_TYPE_ERROR:
                                        throw new RuntimeException("数据类型错误");
                                }

                                System.out.println(value);
                            }
                        }
                    }
                }
                System.out.println("======================================="); // 换行
            }
        }
    }

运行方法得:
在这里插入图片描述
读取成功!!!

完整代码

以下是完整代码:

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
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.joda.time.DateTime;
import org.junit.Test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Date;

/**
 * @ClassName ExcelReadTest
 * @Description excel读取操作
 * @Author 古阙月
 * @Date 2020/11/12 21:58
 * @Version 1.0
 */
public class ExcelReadTest {

    /**
     * 路径
     */
    String PATH = "D:\\IdeaProjects\\my_study_demo\\src\\main\\java\\excel\\read";

    /**
     * 文件名
     */
    String FILENAME = "古阙月的读值示范表03.xls";

    /**
     * 生成一张excel03版本的读值示范表
     * @throws Exception
     */
    @Test
    public void write03Test() throws Exception {

        // 创建一张工作簿
        Workbook workbook = new HSSFWorkbook();
        // 创建一张工作表
        Sheet sheet1 = workbook.createSheet("读值示范");

        /**
         * 创建第一行
         */
        Row row1 = sheet1.createRow(0);
        // 创建第一行第一列
        Cell cell11 = row1.createCell(0);
        // 填值
        cell11.setCellValue("字符串类型");

        // 创建第一行第二列
        Cell cell12 = row1.createCell(1);
        // 填值
        cell12.setCellValue("布尔类型");

        // 创建第一行第三列
        Cell cell13 = row1.createCell(2);
        // 填值
        cell13.setCellValue("空");

        // 创建第一行第四列
        Cell cell14 = row1.createCell(3);
        // 填值
        cell14.setCellValue("数字");

        // 创建第一行第五列
        Cell cell15 = row1.createCell(4);
        // 填值
        cell15.setCellValue("日期");


        /**
         * 创建第二行
         */
        Row row2 = sheet1.createRow(1);
        // 创建第二行第一列
        Cell cell21 = row2.createCell(0);
        // 填值
        cell21.setCellValue("字符串");

        // 创建第二行第二列
        Cell cell22 = row2.createCell(1);
        // 填值
        cell22.setCellValue(true);

        // 创建第二行第三列
        Cell cell23 = row2.createCell(2);
        // 填值
        cell23.setCellValue("");

        // 创建第二行第四列
        Cell cell24 = row2.createCell(3);
        // 填值
        cell24.setCellValue(666666666);

        // 创建第二行第五列
        Cell cell25 = row2.createCell(4);
        // 填值
        cell25.setCellValue(new DateTime().toString("yyyy-MM-dd HH:mm:ss"));

        // 用IO流生成一张Excel表(03版本)- 后缀.xls
        FileOutputStream fileOutputStream = new FileOutputStream(PATH + File.separator + FILENAME);
        // 写入
        workbook.write(fileOutputStream);
        // 关流
        fileOutputStream.close();

        System.out.println(FILENAME + "生成完毕!!!");
    }


    /**
     * excel03版本读取测试
     */
    @Test
    public void readExcel03Test() throws Exception {

        FileInputStream fileInputStream = new FileInputStream(PATH + File.separator + FILENAME);
        // 获取Excel工作簿
        Workbook workbook = new HSSFWorkbook(fileInputStream);
        if (workbook != null) {

            // 获取第一个工作表
            Sheet sheet = workbook.getSheetAt(0);
            if (sheet != null) {

                /**
                 * 获取标题部分
                 */
                Row rowTitle = sheet.getRow(0); // 获取第一行 - 即标题行
                if (rowTitle != null) {

                    int cellTitles = rowTitle.getPhysicalNumberOfCells(); // 获取第一行的列数
                    for (int i = 0; i < cellTitles; i++) {

                        Cell cell = rowTitle.getCell(i); // 获取对应的列
                        if (cell != null) {
                            System.out.print(cell.getStringCellValue() + " | ");
                        }
                    }
                    System.out.println("\n======================================="); // 换行
                }

                /**
                 * 获取内容部分
                 */
                int rows = sheet.getPhysicalNumberOfRows(); // 获取所有的行数
                for (int i = 1; i < rows; i++) {

                    Row row = sheet.getRow(i); // 获取对应的行
                    if (row != null) {
                        int cells = row.getPhysicalNumberOfCells(); // 获取所有的列数

                        for (int j = 0; j < cells; j++) {
                            // 打印一下 行-列 号
                            System.out.print("[" + i + "-" + j + "]");

                            Cell cell = row.getCell(j); // 获取对应的列
                            if (cell != null) {
                                int cellType = cell.getCellType();
                                Object value = "";

                                switch (cellType) {
                                    case HSSFCell.CELL_TYPE_STRING: // 字符串类型
                                        value = cell.getStringCellValue();
                                        break;
                                    case HSSFCell.CELL_TYPE_BLANK: // 空
                                        break;
                                    case HSSFCell.CELL_TYPE_BOOLEAN: // 布尔类型
                                        value = cell.getBooleanCellValue();
                                        break;
                                    case HSSFCell.CELL_TYPE_NUMERIC: // 数字
                                        if (HSSFDateUtil.isCellDateFormatted(cell)) { // 日期
                                            Date date = cell.getDateCellValue();
                                            value = new DateTime(date).toString("yyyy-MM-dd HH:mm:ss");
                                        }else { // 普通数字
                                            // 转成字符串,以防止过长无法显示
                                            cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                                            value = cell;
//                                            value = cell.getNumericCellValue();
                                        }
                                        break;
                                    case HSSFCell.CELL_TYPE_ERROR:
                                        throw new RuntimeException("数据类型错误");
                                }

                                System.out.println(value);
                            }
                        }
                    }
                }
                System.out.println("======================================="); // 换行
            }
        }
    }
}

往期回顾

以下是往期Excel操作的回顾:

【Apache POI】Excel操作(一):Excel本地写入基本操作的实现

【Apache POI】Excel操作(二):Excel本地写入基本操作的实现(进阶版)

【Apache POI】Excel操作(三):Excel在浏览器端即Web端写入操作的实现

【Apache POI】Excel操作(四):Excel大数据量的写入

参考资料:【狂神说Java】POI及EasyExcel一小时搞定通俗易懂

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值