zoukankan      html  css  js  c++  java
  • 基于POI 的Excel文件内容比对 -- Java Apache Poi 4.X

    代码结构

    代码运行结果

    测试用例

    工具使用前提条件

    待完善的点

    在某些项目中,报表比对是测试的一大内容。比如,在某版本下生成baseline report作为标准答案,新代码进来后,再次生成report,跟baseline report作比较,确保改动没有引入差异。报表多以excel文件形式导出,用工具进行excel文件比对十分有用。
    Apache POI 是一个很好的处理microsoft office documents的java库,通过它可以读写word文档,读写Excel文件,读写power point文件,还有visio等等,功能十分强大。

    这里,我建了一个maven项目,使用了poi里面的xssf读.xlsx格式的excel文件(如果想要操作.xls格式的excel文件,则必须使用poi里面的hssf),然后比对source和target文件的差异,并将差异输出。同时使用了JUnit进行代码的单元测试。

    工程已Push至github https://github.com/biantech/compare-excel 。

    使用如下命令运行jar包:

    java - jar excelComparison.jar sourceExcelPath targetExcelPath
     
    代码结构

    代码结构如下图所示:

        SheetData类存储sheet数据:sheet名,sheet有哪些列,sheet的column index与列名的映射关系(Map),最后是sheet的数据(List < List < String> >)
        WorkbookData类则是有若干个SheetData组成(List < SheetData >)
        Utility包里的ExcelUtility类放了用来读excel的静态方法
        最后DifferenceEngine类比较sheet数据并输出差异
        在这里插入图片描述

    代码运行结果

    代码运行结果如下所示,按照sheet输出差异,sheet name取自source excel,Discrepancy summary将所有有差异的列及列名汇总起来(列名取自source excel),接下来按行将source和target单元格不一致的输出
    在这里插入图片描述

    Sheet Name: [Sheet 1]
    Discrepancy summary: Column A(title), Column C(album), Column D(isFound)
    Row 7
        Cell A7: source -- , target -- Title that not in source
        Cell C7: source -- star, target -- @*&
        Cell D7: source -- , target -- 0
    Row 8
        Target row null...
    Row 9
        Target row null...
    Row 10
        Target row null...
    ----------------------------------------------------
    Sheet Name: [Sheet 2]
    Discrepancy summary: Column A(555)
    Row 3
        Cell A3: source -- , target -- 777
    ----------------------------------------------------
    Source excel does not have sheet 3

        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19

    测试用例

    已经在如下场景测试过工具,运行结果无误:

        普通情况下source和target sheet/行/列数量都一致时,source和target的差异正确识别输出
        source cell或者target cell为空时,差异正确识别输出
        source sheet和target sheet行数不一致时,工具正常运行并输出
        source sheet和target sheet列数不一致时,工具正常运行并输出
        source和target的sheet数量不一致,工具正常运行并输出

    工具使用前提条件

    要想工具正常运行,必须满足以下条件:

        必须是2007版的excel
        excel文件里的列名不为空
        source excel和target excel里面的sheet必须是正确对应的,工具不会按照sheet name去匹配它们
        source excel和target excel里的列名必须是正确对应的,工具不会智能去匹配它们

    待完善的点

    目前所有单元格都是按照String进行严格比对的。有些时候如果数值差异在一定范围内也可以接受的话,工具则处理不了。后续可以添加配置文件,由用户自行配置各个列的格式(String,或者value,或者date等等),以及value的tolerance
  • 相关阅读:
    Redis面试题
    spring boot错误: 找不到或无法加载主类
    JAVA的高并发编程
    Redis多机多节点集群实验
    Redis单机多节点集群实验
    Redis集群概述
    Redis的持久化之AOF方式
    Redis的持久化之RDB方式
    Redis持久化介绍
    Redis Keys的通用操作
  • 原文地址:https://www.cnblogs.com/halberts/p/14975003.html
Copyright © 2011-2022 走看看