实现思路:

1.获取WorkBook对象,在这里使用WorkbookFactory.create(is); // 这种方式解析Excel、2003/2007/2010都没问题;

2.对行数据进行解析

  (1)首先第一行作为标题,即和基础类的字段名要保持一致。

  (2)根据传入的Class创建实例

  (3)利用反射,获取方法名,执行方法

Method method = cls.getDeclaredMethod(methodName,cls.getDeclaredField(title).getType());
method.invoke(obj, value);

  (4)将创建的对象加入到集合

需要的jar文件:

所有的jar文件均可以在http://poi.apache.org中找到

具体实现代码细节:

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
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.usermodel.WorkbookFactory; /**
* 解析一个Excel表格,将其存放到一个对象集合中
*
* @author jingang
*
*/
public class ReadExcel { /**
* 传入一Excel表格,创建出对应的类集合 要求: 类的字段名必须和Excel的首行的标题相同
*
* @param filePath
* @param cls
* @return
* @throws InvalidFormatException
* @throws IOException
* @throws InstantiationException
* @throws IllegalAccessException
* @throws NoSuchMethodException
* @throws SecurityException
* @throws NoSuchFieldException
* @throws IllegalArgumentException
* @throws InvocationTargetException
*/
public static List readExcel(String filePath, Class cls) throws InvalidFormatException, IOException,
InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException,
NoSuchFieldException, IllegalArgumentException, InvocationTargetException {
File excelFile = new File(filePath);
FileInputStream is = new FileInputStream(excelFile); // 文件流
Workbook workbook = WorkbookFactory.create(is); // 这种方式完美支持Excel、2003/2007/2010
Sheet sheet = workbook.getSheetAt(0);// 获取工作区(只提取第一个工作区)
int rowCount = sheet.getPhysicalNumberOfRows();// 文件的总行数
List<Object> objList = new ArrayList<>();// 对象的集合
Row row1 = sheet.getRow(0);// 获得首行表示,单元格的内容必须与pojo类的字段名一致
for (int i = 1; i < rowCount; i++) {
// 解析每一行
Row row = sheet.getRow(i);
Object obj = cls.newInstance();// 反射创建对象
for (int j = 0; j < row1.getPhysicalNumberOfCells(); j++) {
String title = row1.getCell(j).getStringCellValue();
String methodName = "set" + title.substring(0, 1).toUpperCase() + title.substring(1);
Cell cell = row.getCell(j);
if (cell != null) {
if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
int value = (int) cell.getNumericCellValue();
Method method = cls.getDeclaredMethod(methodName, cls.getDeclaredField(title).getType());
method.invoke(obj, value);
}
//这里可根据需要,增加对其它数据类型的判断
} else {
Method method = cls.getDeclaredMethod(methodName, cls.getDeclaredField(title).getType());
method.invoke(obj, 0);
}
}
objList.add(obj);
}
return objList;
}
}

该方法目前只是形成了一个初步的模型,仍还有许多需要改进的。譬如:

1.这里只支持了表格中的int数据类型;

2.对于方法耗时太长,可能在使用WorkbookFactory.create(is);的地方耗时太长。

希望各位有好的想法或者改进,敬请指教,多谢!

POI完美解析Excel数据到对象集合中(可用于将EXCEL数据导入到数据库)的更多相关文章

  1. Java基础知识强化之IO流笔记46:IO流练习之 把文本文件中数据存储到集合中的案例

    1.  把文本文件中数据存储到集合中      需求:从文本文件中读取数据(每一行为一个字符串数据)到集合中,并遍历集合. 分析:      通过题目的意思我们可以知道如下的一些内容,      数据 ...

  2. 使用Properties集合存储数据,遍历取出Properties集合中的数据和Properties集合中的方法store和load

    package com.yang.Test.PropertiesStudy; import java.io.FileWriter; import java.io.IOException; import ...

  3. java8 从对象集合中取出某个字段的集合

    public class FeildTest { public static void main(String[] args) { //定义list集合 List<P> list = Ar ...

  4. ANDROID_MARS学习笔记_S02_015_Gson解析json串为对象集合

    package com.example.s02_e12_json3; import java.lang.reflect.Type; import java.util.Iterator; import ...

  5. python实例:在列表,字典,集合中,根据条件筛选数据

    1. 从列表中过滤掉 负数 from random import randint # 随机生成列表 data = [randint(-10, 10) for _ in range(10)] print ...

  6. .NET[C#]使用LINQ从List<T>集合中获取最后N条数据记录的方法有哪些?

    https://codedefault.com/2018/using-linq-to-get-the-last-n-elements-of-a-collection-in-csharp-applica ...

  7. 阶段1 语言基础+高级_1-3-Java语言高级_06-File类与IO流_06 Properties集合_1_使用Properties集合存储数据,遍历取出集合中的数据

    map下面的实现类叫做Hashtable Properties是唯一和IO流相结合的 讲解 代码

  8. Jmeter beanshell把数据写入csv文件中,最后清除csv数据

    有时候我们需要使用jmeter去结合csv文件去做一些简单的数据驱动处理: 例如把数据库数据黏贴到csv文件中或者把网页上的数据填入到csv文件中: 直接我一般是用手自己黏贴复制过csv文件中,比较麻 ...

  9. MVC传递数据-传递对象或对象集合

    前言 本文主要介绍从View(或者js)文件向Controller提交对象或者对象集合.比方.将表格中的一行数据作为一个对象提交.或将多行数据作为一个集合提交到Controller. 回想 从View ...

随机推荐

  1. jdk 环境变量配置

    环境变量:Path %JAVA_HOME%\bin;%JAVA_HOME%\jre\binCLASSPATH .;%JAVA_HOME%\lib;JAVA_HOME D:\java\jdk1.5.0_ ...

  2. pureftp在centos下与MySQL搭配使用

    概述 pure-ftpd是linux下的一个ftp服务端,据说安全性较高.我在centos6下用yum安装pure-ftpd,并配置了通过MySQL进行用户的增删改查,以及对应到apache的web目 ...

  3. [转] C++的引用传递、指针传递参数在java中的相应处理方法

    原文出处:[http://blog.csdn.net/conowen/article/details/7420533] 首先要明白一点,java是没有指针这个概念的. 但是要实现C++的引用传递.指针 ...

  4. git 提交代码

    git config --global user.name=a_name git config --global user.email=an_email_address mkdir test cd t ...

  5. Theano Graph Structure

    Graph Structure Graph Definition theano's symbolic mathematical computation, which is composed of: A ...

  6. 仿浏览器TAB效果

    仿浏览器的Tag标签 这里先上个非常非常简陋的demo,没加CSS,我先把jquery的源码给全部搞通,在专心把这个功能给讲一下 <!doctype html> <html lang ...

  7. nginx服务器命令

    nginx -s reload  :修改配置后重新加载生效 nginx -s reopen  :重新打开日志文件nginx -t -c /path/to/nginx.conf 测试nginx配置文件是 ...

  8. GridView利用PagerTemplate做分页显示设置上一页下一页转到下拉转页

    效果如图: 代码如下: aspx页: <asp:GridView ID="GridViewMain" runat="server" OnPageIndex ...

  9. Android广播接收器BroadcastRceiver

    一.使用BroadcastRceiver 1.创建BroadcastRceiver(MyRceiver),重写OnReceiver: public void onReceive(Context con ...

  10. hdu2211杀人游戏

    Problem Description 不知道你是否玩过杀人游戏,这里的杀人游戏可没有法官,警察之类的人,只有土匪,现在已知有N个土匪站在一排,每个土匪都有一个编号,从1到N,每次杀人时给定一个K值, ...