java POI 读写 excel(项目实际需求)

本贴最后更新于 4243 天前,其中的信息可能已经时过境迁

这几天由于工作需要,需要做一个报表比对工具(找出两张报表的差异)。需求如下

1、做一个客户端工具,采用java,可以不用GUI(考虑到,我目前只懂j2ee相关的技术,其实这个需求用python(python版本)来做是最合适的,可是我目前不会,当然后面我会学习下这们语言)

2、两张报表的比队列需要灵活配置,通过配置文件来控制需要比对的列(可以是一列,可以是多列)

3、需要找出表A中有的一条数据,但是表B中没有的。或者表B中有的,表A中没有的。或者表A和表B同时都存在的一条数据,但是里面的某一些字段不一样。

4、两张报表的格式可能不一样,有可能为csv,xls,xlsx。两张报表的列数也是不固定的(这两张报表可以是任意的两张报表)

5、将比对结果再汇总到一张excel中(格式没有要求,我这里默认的是xls)

6、主键可能为复合主键,比对的报表,可能需要一次比对多组报表(由于这个需求,是今天才加上的,所以目前代码还处理这个问题,当然会很快加上)

思路一:

POI1-1

1、采用二维数组为主要的数据结构。因为,报表的列数不确定,所以不能构造对象,采用下标来控制每一列

2、将A表中的第一行的主键,然后搜索表B的主键,如果没搜到记下来,如果搜到了,比较所配置的列看是否相同,如果不同记下来,再反搜,表B中的主键来搜素表A,如果表B中有的,表A中没有的,记下来。

将记下来的数据重组,再导出excel。

效率:两张表都是30多列,52行,大概一秒左右比对完导出到excel中。

思路二

 POI1-2

1、主要采用了循环加map的方式,再比较是否有相等行的时候,直接用,表A的mapA.get(mapB.get("key"))如果数据不为空,说明在表A中有数据和表B匹配,这里的get有效的减少了一次循环。利用了map.get的方法速度更快。其他的。但是主要逻辑,还是如思路相同

接下来贴出,处理这个需求的主要代码。贴出代码的目的,主要是希望各位网友看到后,能够给指点一二,我这代码,肯定还需要优化,重构。或者说换思路。当然你有什么想法,通过评论,或者邮件告诉我。谢谢

ReadCSVExcel方法

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

import au.com.bytecode.opencsv.CSVReader;

import com.qly.report.operate.facade.IReadExcel;

public class ReadCsvImpl implements IReadExcel{
static String qlyStringArr[][] = new String[1000][1000];
static String otherStringArr[][] = new String[1000][1000];
static Map<String,Integer > qlycontent = new HashMap<String,Integer >();
static Map<String,Integer > othercontent = new HashMap<String,Integer >();

@Override public Map&lt;String, Object&gt; readExcel(String path, String flag) { CSVReader reader = null; // 取特定列放到集合 try { InputStream ins = new FileInputStream(new File(path)); InputStreamReader in = new InputStreamReader(ins, &quot;gbk&quot;); reader = new CSVReader(in); int len = reader.readNext().length; String nextline[]; int counter = 0; // 将不同的来源的csv文件分别存放到不同的二维数组中 if (&quot;qly&quot;.equals(flag)) { Map&lt;String, Object&gt; qlyMap = new HashMap&lt;String, Object&gt;(); while ((nextline = reader.readNext()) != null) { for (int i = 0; i &lt; len; i++) { qlyStringArr[counter][i] = nextline[i]; } counter++; } qlycontent.put(&quot;colNum&quot;, len); qlycontent.put(&quot;rowNum&quot;, counter); qlyMap.put(&quot;qlyStringArr&quot;, qlyStringArr); qlyMap.put(&quot;qlycontent&quot;, qlycontent); return qlyMap; } if (&quot;other&quot;.equals(flag)) { Map&lt;String, Object&gt; otherMap = new HashMap&lt;String, Object&gt;(); while ((nextline = reader.readNext()) != null) { for (int i = 0; i &lt; len; i++) { otherStringArr[counter][i] = nextline[i]; } counter++; } othercontent.put(&quot;colNum&quot;, len); othercontent.put(&quot;rowNum&quot;, counter); otherMap.put(&quot;othercontent&quot;, othercontent); otherMap.put(&quot;otherStringArr&quot;, otherStringArr); return otherMap; } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } return null; }

}

ReadXlsExcel 方法

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFCell;
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.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.qly.report.operate.facade.IReadExcel;
import com.qly.report.util.ReportUtil;

public class ReadXlsImpl implements IReadExcel{

public static HSSFWorkbook wb = null; public static HSSFSheet hssfSheet =null; public static HSSFRow hssfRow = null; public static XSSFWorkbook xb = null; public static XSSFSheet xssfSheet =null; public static XSSFRow xssfRow =null; public static String qlyStringArr[][] = new String[1000][1000]; public static String otherStringArr[][] = new String[1000][1000]; static Map&lt;String,Integer &gt; qlycontent = new HashMap&lt;String,Integer &gt;(); static Map&lt;String,Integer &gt; othercontent = new HashMap&lt;String,Integer &gt;(); @SuppressWarnings({ &quot;deprecation&quot; }) @Override public Map&lt;String ,Object&gt; readExcel(String path, String flag) { int counter = 0; try { InputStream is = new FileInputStream(new File(path)); wb = new HSSFWorkbook(is); hssfSheet = wb.getSheetAt(0); // 得到总行数 int rowNum = hssfSheet.getLastRowNum(); hssfRow = hssfSheet.getRow(1); int colNum = hssfRow.getPhysicalNumberOfCells(); // 正文内容应该从第二行开始,第一行为表头内容 if(&quot;qly&quot;.equals(flag)){ Map&lt;String,Object&gt;qlyMap = new HashMap&lt;String, Object&gt;(); for (int i = 1; i &lt; rowNum; i++) { hssfRow = hssfSheet.getRow(i); counter = 0; while (counter &lt; colNum) { qlyStringArr[i][counter] = get2003StringCellValue( hssfRow.getCell((short)counter)).trim(); counter++; } } qlycontent.put(&quot;colNum&quot;, counter); qlycontent.put(&quot;rowNum&quot;, rowNum); qlyMap.put(&quot;qlyStringArr&quot;, qlyStringArr); qlyMap.put(&quot;qlycontent&quot;, qlycontent); return qlyMap; } if(&quot;other&quot;.equals(flag)){ Map&lt;String,Object&gt;otherMap = new HashMap&lt;String, Object&gt;(); for (int i =1; i &lt; rowNum; i++) { hssfRow = hssfSheet.getRow(i); counter = 0; while (counter &lt; colNum) { otherStringArr[i][counter] = get2003StringCellValue(hssfRow.getCell((short) counter)).trim(); counter++; } } othercontent.put(&quot;colNum&quot;, counter); othercontent.put(&quot;rowNum&quot;, rowNum); otherMap.put(&quot;othercontent&quot;, othercontent); otherMap.put(&quot;otherStringArr&quot;, otherStringArr); return otherMap; } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } private static String get2003StringCellValue(HSSFCell cell) { String strCell = &quot;&quot;; if (null == cell) { return &quot;&quot;; } switch (cell.getCellType()) { case HSSFCell.CELL_TYPE_STRING: strCell = cell.getStringCellValue(); break; case HSSFCell.CELL_TYPE_NUMERIC: //使用DecimalFormat类对科学计数法格式的数字进行格式化 DecimalFormat df = new DecimalFormat(&quot;#&quot;); String str = String.valueOf(cell.getNumericCellValue()); if(ReportUtil.isNumber(str)){ strCell = df.format(cell.getNumericCellValue()); }else{ strCell = str; } break; case HSSFCell.CELL_TYPE_BOOLEAN: strCell = String.valueOf(cell.getBooleanCellValue()); break; case HSSFCell.CELL_TYPE_BLANK: strCell = &quot;&quot;; break; default: strCell = &quot;&quot;; break; } if (strCell.equals(&quot;&quot;) || null == strCell) { return &quot;&quot;; } return strCell; }

}

ReadXlsxExcel方法

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;

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.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 com.qly.report.operate.facade.IReadExcel;
import com.qly.report.util.ReportUtil;

public class ReadXlsxImpl implements IReadExcel {
public static HSSFWorkbook wb = null;
public static HSSFSheet hssfSheet =null;
public static HSSFRow hssfRow = null;
public static XSSFWorkbook xb = null;
public static XSSFSheet xssfSheet =null;
public static XSSFRow xssfRow =null;
public static String qlyStringArr[][] = new String[1000][1000];
public static String otherStringArr[][] = new String[1000][1000];
static Map<String,Integer > qlycontent = new HashMap<String,Integer >();
static Map<String,Integer > othercontent = new HashMap<String,Integer >();
@Override
public Map<String,Object> readExcel(String path, String flag) {
int counter = 0;
try {
InputStream is = new FileInputStream(new File(path));

xb = new XSSFWorkbook(is); xssfSheet = xb.getSheetAt(0); // 得到总行数 int rowNum = xssfSheet.getLastRowNum(); xssfRow = xssfSheet.getRow(1); int colNum = xssfRow.getPhysicalNumberOfCells(); // 正文内容应该从第二行开始,第一行为表头内容 if(&quot;qly&quot;.equals(flag)){ Map&lt;String,Object&gt;qlyMap = new HashMap&lt;String, Object&gt;(); for (int i = 1; i &lt; rowNum; i++) { xssfRow = xssfSheet.getRow(i); counter = 0; while (counter &lt; colNum) { qlyStringArr[i][counter] = get2007StringCellValue( xssfRow.getCell((short) counter)).trim(); counter++; } } qlycontent.put(&quot;colNum&quot;, counter); qlycontent.put(&quot;rowNum&quot;, rowNum); qlyMap.put(&quot;qlyStringArr&quot;, qlyStringArr); qlyMap.put(&quot;qlycontent&quot;, qlycontent); return qlyMap; } if(&quot;other&quot;.equals(flag)){ Map&lt;String,Object&gt;otherMap = new HashMap&lt;String, Object&gt;(); for (int i = 1; i &lt; rowNum; i++) { xssfRow = xssfSheet.getRow(i); counter = 0; while (counter &lt; colNum) { otherStringArr[i][counter] = get2007StringCellValue( xssfRow.getCell((short) counter)).trim(); counter++; } } othercontent.put(&quot;colNum&quot;, counter); othercontent.put(&quot;rowNum&quot;, rowNum); otherMap.put(&quot;othercontent&quot;, othercontent); otherMap.put(&quot;otherStringArr&quot;, otherStringArr); return otherMap; } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } private static String get2007StringCellValue(XSSFCell cell) { String strCell = &quot;&quot;; if (null == cell) { return &quot;&quot;; } switch (cell.getCellType()) { case XSSFCell.CELL_TYPE_STRING: strCell = cell.getStringCellValue(); break; case XSSFCell.CELL_TYPE_NUMERIC: //使用DecimalFormat类对科学计数法格式的数字进行格式化 DecimalFormat df = new DecimalFormat(&quot;#&quot;); String str = String.valueOf(cell.getNumericCellValue()); if(ReportUtil.isNumber(str)){ strCell = df.format(cell.getNumericCellValue()); }else{ strCell = str; } break; case XSSFCell.CELL_TYPE_BOOLEAN: strCell = String.valueOf(cell.getBooleanCellValue()); break; case XSSFCell.CELL_TYPE_BLANK: strCell = &quot;&quot;; break; default: strCell = &quot;&quot;; break; } if (strCell.equals(&quot;&quot;) || null == strCell) { return &quot;&quot;; } return strCell; }

}

 

 

CompareExcel方法,比较算法在这里

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.qly.report.operate.facade.ICompareExcel;
import com.qly.report.util.ReportUtil;
/**

  • by guop 2013-7-12 上午 9:11:06

  • 比较 excel
    */
    public class CompareExcelImpl implements ICompareExcel{

    @Override
    public Map<String ,Object> compareExcel(String [][] qlyString, String [][] otherString,
    int[] qlycolumn, int[] othercolumn,
    Map<String,Integer> qlycontent, Map<String,Integer> othercontent,
    int qlyflag, int otherflag, int qlystartRow, int otherstartRow,
    String outReportPath) {

    // 761报表的行数 int qlyRowNum = qlycontent.get(&quot;rowNum&quot;); // 761报表的列数 int otherRowNum = othercontent.get(&quot;rowNum&quot;); List&lt;Map&lt;String, Integer&gt;&gt; listErrorStr = new ArrayList&lt;Map&lt;String, Integer&gt;&gt;(); // 在这里比较下,用a表的标记字段扫描b表从1开始,0为表头 for (int i = qlystartRow; i &lt; qlyRowNum; i++) { boolean boolflag = false; boolean boolother = true; Map&lt;String, Integer&gt; errorMap = new HashMap&lt;String, Integer&gt;(); for (int j = otherstartRow; j &lt; otherRowNum; j++) { // 按照配置的标记列,如761中的票号,和腾邦的票号 // 表a中的第一行某字段,遍历表b中的行中的这一字段,看是否相同0 if (ReportUtil.handleSpecialCharacter(qlyString[i][qlyflag].trim()).equals(ReportUtil.handleSpecialCharacter(otherString[j][otherflag].trim()))) { boolother = false; int rowother = j; // 在寻找到b表中,有相同的字段后,比较其他字段是否相同 for (int a1 = 0; a1 &lt; qlycolumn.length;a1++) { if(null == qlyString[i][qlycolumn[a1]] || null == otherString[rowother][othercolumn[a1]]){ break; } // 当a表和b表中的 票面号相同,比较里面的规定的字段的值是否相同 if (!ReportUtil.handleSpecialCharacter(qlyString[i][qlycolumn[a1]].trim()).equals(ReportUtil.handleSpecialCharacter(otherString[rowother][othercolumn[a1]].trim()))) { errorMap.put(&quot;qlylinenumber&quot;, i); errorMap.put(&quot;otherlinenumber&quot;, rowother); listErrorStr.add(errorMap); boolflag = true; break; } } if (boolflag) { break; } } } if (boolother) { errorMap.put(&quot;qlylinenumber&quot;, i); listErrorStr.add(errorMap); } } //用b表扫描a表的某一个字段 // 在这里比较下,用a表的标记字段扫描b表 for (int i = otherstartRow; i &lt; otherRowNum; i++) { boolean boolother = true; Map&lt;String, Integer&gt; errorMap = new HashMap&lt;String, Integer&gt;(); for (int j = qlystartRow; j &lt; qlyRowNum; j++) { // 按照配置的标记列,如761中的票号,和腾邦的票号 // 表a中的第一行某字段,遍历表b中的行中的这一字段,看是否相同0 if (ReportUtil.handleSpecialCharacter(qlyString[j][qlyflag].trim()).equals(ReportUtil.handleSpecialCharacter(otherString[i][otherflag].trim()))) { boolother = false; // 在寻找到b表中,有相同的字段后,比较其他字段是否相同 } } if (boolother) { errorMap.put(&quot;otherlinenumber&quot;, i); listErrorStr.add(errorMap); } } Map&lt;String,Object&gt; compareMap = new HashMap&lt;String, Object&gt;(); compareMap.put(&quot;listErrorStr&quot;, listErrorStr);

    return compareMap;
    }

}

全部代码在这里,github,请多多指教

  • POI
    23 引用 • 21 回帖
  • Excel
    31 引用 • 28 回帖
  • Java

    Java 是一种可以撰写跨平台应用软件的面向对象的程序设计语言,是由 Sun Microsystems 公司于 1995 年 5 月推出的。Java 技术具有卓越的通用性、高效性、平台移植性和安全性。

    3194 引用 • 8214 回帖

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...
  • someone

    老船长这个不是专栏是博客吧。哈哈。专栏不是这个意思吧。

推荐标签 标签

  • Sublime

    Sublime Text 是一款可以用来写代码、写文章的文本编辑器。支持代码高亮、自动完成,还支持通过插件进行扩展。

    10 引用 • 5 回帖
  • etcd

    etcd 是一个分布式、高可用的 key-value 数据存储,专门用于在分布式系统中保存关键数据。

    6 引用 • 26 回帖 • 546 关注
  • 自由行
    3 关注
  • Solo

    Solo 是一款小而美的开源博客系统,专为程序员设计。Solo 有着非常活跃的社区,可将文章作为帖子推送到社区,来自社区的回帖将作为博客评论进行联动(具体细节请浏览 B3log 构思 - 分布式社区网络)。

    这是一种全新的网络社区体验,让热爱记录和分享的你不再感到孤单!

    1440 引用 • 10067 回帖 • 489 关注
  • 强迫症

    强迫症(OCD)属于焦虑障碍的一种类型,是一组以强迫思维和强迫行为为主要临床表现的神经精神疾病,其特点为有意识的强迫和反强迫并存,一些毫无意义、甚至违背自己意愿的想法或冲动反反复复侵入患者的日常生活。

    15 引用 • 161 回帖
  • Windows

    Microsoft Windows 是美国微软公司研发的一套操作系统,它问世于 1985 年,起初仅仅是 Microsoft-DOS 模拟环境,后续的系统版本由于微软不断的更新升级,不但易用,也慢慢的成为家家户户人们最喜爱的操作系统。

    226 引用 • 476 回帖
  • Node.js

    Node.js 是一个基于 Chrome JavaScript 运行时建立的平台, 用于方便地搭建响应速度快、易于扩展的网络应用。Node.js 使用事件驱动, 非阻塞 I/O 模型而得以轻量和高效。

    139 引用 • 269 回帖
  • Docker

    Docker 是一个开源的应用容器引擎,让开发者可以打包他们的应用以及依赖包到一个可移植的容器中,然后发布到任何流行的操作系统上。容器完全使用沙箱机制,几乎没有性能开销,可以很容易地在机器和数据中心中运行。

    494 引用 • 928 回帖
  • webpack

    webpack 是一个用于前端开发的模块加载器和打包工具,它能把各种资源,例如 JS、CSS(less/sass)、图片等都作为模块来使用和处理。

    41 引用 • 130 回帖 • 254 关注
  • Latke

    Latke 是一款以 JSON 为主的 Java Web 框架。

    71 引用 • 535 回帖 • 819 关注
  • 思源笔记

    思源笔记是一款隐私优先的个人知识管理系统,支持完全离线使用,同时也支持端到端加密同步。

    融合块、大纲和双向链接,重构你的思维。

    24764 引用 • 101803 回帖
  • Maven

    Maven 是基于项目对象模型(POM)、通过一小段描述信息来管理项目的构建、报告和文档的软件项目管理工具。

    186 引用 • 318 回帖 • 262 关注
  • OpenShift

    红帽提供的 PaaS 云,支持多种编程语言,为开发人员提供了更为灵活的框架、存储选择。

    14 引用 • 20 回帖 • 650 关注
  • InfluxDB

    InfluxDB 是一个开源的没有外部依赖的时间序列数据库。适用于记录度量,事件及实时分析。

    2 引用 • 85 关注
  • Postman

    Postman 是一款简单好用的 HTTP API 调试工具。

    4 引用 • 3 回帖 • 1 关注
  • ReactiveX

    ReactiveX 是一个专注于异步编程与控制可观察数据(或者事件)流的 API。它组合了观察者模式,迭代器模式和函数式编程的优秀思想。

    1 引用 • 2 回帖 • 175 关注
  • Kafka

    Kafka 是一种高吞吐量的分布式发布订阅消息系统,它可以处理消费者规模的网站中的所有动作流数据。 这种动作(网页浏览,搜索和其他用户的行动)是现代系统中许多功能的基础。 这些数据通常是由于吞吐量的要求而通过处理日志和日志聚合来解决。

    36 引用 • 35 回帖
  • OneNote
    1 引用 • 3 回帖 • 1 关注
  • RESTful

    一种软件架构设计风格而不是标准,提供了一组设计原则和约束条件,主要用于客户端和服务器交互类的软件。基于这个风格设计的软件可以更简洁,更有层次,更易于实现缓存等机制。

    30 引用 • 114 回帖 • 6 关注
  • Oracle

    Oracle(甲骨文)公司,全称甲骨文股份有限公司(甲骨文软件系统有限公司),是全球最大的企业级软件公司,总部位于美国加利福尼亚州的红木滩。1989 年正式进入中国市场。2013 年,甲骨文已超越 IBM,成为继 Microsoft 后全球第二大软件公司。

    107 引用 • 127 回帖 • 357 关注
  • FFmpeg

    FFmpeg 是一套可以用来记录、转换数字音频、视频,并能将其转化为流的开源计算机程序。

    23 引用 • 32 回帖 • 1 关注
  • GAE

    Google App Engine(GAE)是 Google 管理的数据中心中用于 WEB 应用程序的开发和托管的平台。2008 年 4 月 发布第一个测试版本。目前支持 Python、Java 和 Go 开发部署。全球已有数十万的开发者在其上开发了众多的应用。

    14 引用 • 42 回帖 • 804 关注
  • AngularJS

    AngularJS 诞生于 2009 年,由 Misko Hevery 等人创建,后为 Google 所收购。是一款优秀的前端 JS 框架,已经被用于 Google 的多款产品当中。AngularJS 有着诸多特性,最为核心的是:MVC、模块化、自动化双向数据绑定、语义化标签、依赖注入等。2.0 版本后已经改名为 Angular。

    12 引用 • 50 回帖 • 501 关注
  • 阿里云

    阿里云是阿里巴巴集团旗下公司,是全球领先的云计算及人工智能科技公司。提供云服务器、云数据库、云安全等云计算服务,以及大数据、人工智能服务、精准定制基于场景的行业解决方案。

    84 引用 • 324 回帖
  • BND

    BND(Baidu Netdisk Downloader)是一款图形界面的百度网盘不限速下载器,支持 Windows、Linux 和 Mac,详细介绍请看这里

    107 引用 • 1281 回帖 • 29 关注
  • HBase

    HBase 是一个分布式的、面向列的开源数据库,该技术来源于 Fay Chang 所撰写的 Google 论文 “Bigtable:一个结构化数据的分布式存储系统”。就像 Bigtable 利用了 Google 文件系统所提供的分布式数据存储一样,HBase 在 Hadoop 之上提供了类似于 Bigtable 的能力。

    17 引用 • 6 回帖 • 62 关注
  • 互联网

    互联网(Internet),又称网际网络,或音译因特网、英特网。互联网始于 1969 年美国的阿帕网,是网络与网络之间所串连成的庞大网络,这些网络以一组通用的协议相连,形成逻辑上的单一巨大国际网络。

    99 引用 • 367 回帖