借助jxl将Excel中的数据注入到Bean中
前言
使用了Hibernate的项目中需要导入多张表的数据,但是我又不想写多次取出Excle数据放到Bean里的代码,于是写了个ExcleUtils来帮助我做这件事。
基本思路
技术上,首先肯定是要借助反射的,然后选择了jxl来操作Excle。
需要的参数上,Excle文件不能少;好像没有什么方法能够在Excel隐藏地放入对应属性名的信息(就是属性名字不会在Excle中显示出来,如果有方法能够做到,请给我留言,多谢!),于是我会需要按照Excle顺序的属性名称数组;然后我需要在Sheet页的序号以及数据从第几行开始;对于Date类型,可能需要SimpleDateFormat对象来进行转换,如果没有就使用默认的。因此这个方法应该是这样的(并且有一个重载版本):
public static <T> List<T> getDataList(File excelFile, int sheetindex,
int start, String[] props, Class<T> clazz) throws Exception {
return getDataList(excelFile, sheetindex, start, props, clazz, null);
}
public static <T> List<T> getDataList(File excelFile, int sheetindex,
int start, String[] props, Class<T> clazz, SimpleDateFormat sdf) {
//TODO
}
实现
本来想把代码拆开说说自己的思路,想了想还是整块代码贴上然后写注释把(只贴相关部分的),其实都蛮简单的。
private static final Map<Class<?>, Class<?>> pwMap = new HashMap<Class<?>, Class<?>>();
static {
pwMap.put(byte.class, Byte.class);
pwMap.put(short.class, Short.class);
pwMap.put(int.class, Integer.class);
pwMap.put(long.class, Long.class);
pwMap.put(float.class, Float.class);
pwMap.put(double.class, Double.class);
pwMap.put(boolean.class, Boolean.class);
pwMap.put(char.class, Character.class);
}
private ExcelUtils() {
}
/**
* <p>
* 从Excel中获取对象列
* </p>
*
* @param excelFile
* 文件
* @param sheetindex
* 第几个sheet
* @param props
* 属性名(按顺序) (如果有非基本类型需要实现valueOf方法)
* @param clazz
* 类型
* @return
* @throws Exception
* String[], Class, SimpleDateFormat)
*/
public static <T> List<T> getDataList(File excelFile, int sheetindex,
int startRow, int startCol, String[] props, Class<T> clazz)
throws Exception {
return getDataList(excelFile, sheetindex, startRow, startCol, props,
clazz, null);
}
/**
*
* @param excelFile
* Excel文件
* @param sheetindex
* @param start
* @param props
* @param clazz
* @param sdf
* @return
* @throws Exception
*/
public static <T> List<T> getDataList(File excelFile, int sheetindex,
int startRow, int startCol, String[] props, Class<T> clazz,
SimpleDateFormat sdf) throws Exception {
Workbook excel = null;
try {
excel = Workbook.getWorkbook(excelFile);
Sheet sheet = excel.getSheet(sheetindex);
int n = sheet.getRows();
List<T> result = new ArrayList<T>(n);
for (int i = startRow; i < n; i++) {
Cell[] row = sheet.getRow(i);
result.add(getRowData(props, row, clazz, sdf, startCol));
}
return result;
} catch (BiffException | IOException e) {
throw new Exception("读取Excel文件出错!");
} finally {
excel.close();
}
}
/**
* <p>
* 获取其中一行的数据注入到对象中
* </p>
*
* @param props
* @param row
* @param clazz
* @return
* @throws Exception
*/
public static <T> T getRowData(String[] props, Cell[] row, Class<T> clazz,
int startCol) throws Exception {
return getRowData(props, row, clazz, null, startCol);
}
/**
*
* @param props
* @param row
* @param clazz
* @param sdf
* @return
* @throws Exception
*/
public static <T> T getRowData(String[] props, Cell[] row, Class<T> clazz,
SimpleDateFormat sdf, int startCol) throws Exception {
// 属性首字母大写
for (int i = 0; i < props.length; i++) {
if (props[i] == null)
continue;
StringBuilder sb = new StringBuilder(props[i]);
sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));
props[i] = sb.toString();
}
// 实例化一个对象
T result = clazz.newInstance();
for (int i = 0; i < props.length; i++) {
String propName = props[i];
if (propName == null) {
continue;
}
Class<?> type = getPropType(clazz, propName);
// 把getter的返回类型作为参数类型获取setter
Method setter = clazz.getMethod("set" + propName, type);
String contents = row[i + startCol].getContents();
if (contents != null) {
Object val = string2Type(contents, type, sdf);
// 执行setter
setter.invoke(result, val);
}
}
return result;
}
private static final SimpleDateFormat DEFALUT_SIMPLEDATEF = new SimpleDateFormat(
"yyyy-MM-dd");
@SuppressWarnings("unchecked")
private static <T> T string2Type(String val, Class<T> clazz,
SimpleDateFormat sdf) throws Exception {
Method valueOf = null;
// 对Date和String特殊处理
if (String.class == clazz) {
return (T) val;
}
if (Date.class == clazz) {
return (T) (sdf != null ? sdf.parse(val) : DEFALUT_SIMPLEDATEF
.parse(val));
}
if (char.class == clazz || Character.class == clazz) {
Character c = val.toCharArray().length > 0 ? val.toCharArray()[0]
: (Character.class == clazz ? null : (char) 0);
return (T) c;
}
// 对基本类型做处理
Class<?> finalclazz = clazz.isPrimitive() ? pwMap.get(clazz) : clazz;
try {
valueOf = finalclazz.getMethod("valueOf", String.class);
} catch (NoSuchMethodException e) {
throw new Exception("成员类型需要有T valueOf(String)静态方法");
}
return (T) valueOf.invoke(null, val);
}
private static Class<?> getPropType(Class<?> clazz, String propName)
throws NoSuchMethodException, SecurityException {
Method getter = clazz.getMethod("get" + propName);
Class<?> type = getter.getReturnType();
return type;
}
借助jxl将Excel中的数据注入到Bean中的更多相关文章
- 使用OpenXml把Excel中的数据导出到DataSet中
public class OpenXmlHelper { /// <summary> /// 读取Excel数据到DataSet中,默认读取所有Sheet中的数据 /// </sum ...
- excel文件与txt文件互转,并且把excel里的数据导入到oracle中
一.excel文件转换成txt文件的步骤 a.首先要把excel文件转换成txt文件 1.Excel另存为中已经包含了TXT格式,所以我们可以直接将Excel表格另存为TXT格式,但是最后的效果好像不 ...
- sql之将一个表中的数据注入另一个表中
sql之将一个表中的数据注入另一个表中 需求:现有两张表t1,t2,现需要将t2的数据通过XZQHBM相同对应放入t1表中 t1: t2: 思路:left join 语句: select * from ...
- C# 将Excel里面的数据填充到DataSet中
/// <summary> /// 将Excel表里的数据填充到DataSet中 /// </summary> /// <param name="filenam ...
- C#-WinForm-ListView-表格式展示数据、如何将数据库中的数据展示到ListView中、如何对选中的项进行修改
在展示数据库中不知道数量的数据时怎么展示最好呢?--表格 ListView - 表格形式展示数据 ListView 常用属性 HeaderStyle - "详细信息"视图中列标头的 ...
- 将SQLServer2005中的数据同步到Oracle中
有时由于项目开发的需要,必须将SQLServer2005中的某些表同步到Oracle数据库中,由其他其他系统来读取这些数据.不同数据库类型之间的数据同步我们可以使用链接服务器和SQLAgent来实现. ...
- C# 将List中的数据导入csv文件中
//http://www.cnblogs.com/mingmingruyuedlut/archive/2013/01/20/2849906.html C# 将List中的数据导入csv文件中 将数 ...
- SQL SERVER 使用BULK Insert将txt文件中的数据批量插入表中(1)
1/首先建立数据表 CREATE TABLE BasicMsg( RecvTime FLOAT NOT NULL , --接收时间,不存在时间相同的数据 AA INT NOT NULL, --24位地 ...
- Sql Server中的数据类型和Mysql中的数据类型的对应关系(转)
Sql Server中的数据类型和Mysql中的数据类型的对应关系(转):https://blog.csdn.net/lilong329329/article/details/78899477 一.S ...
随机推荐
- NOIP2013 提高组 Day1
https://www.luogu.org/problem/lists?name=&orderitem=pid&tag=83%7C30 期望得分:100+100+100=300 实际得 ...
- UVA 12063 Zeros and Ones
https://vjudge.net/problem/UVA-12063 题意: 统计n为二进制数中,0和1相等且值为m的倍数的数有多少个 dp[i][j][k] 前i位二进制 有j个1 值模m等于k ...
- 超越icon font
很久以前,我们如何使用图标? 1.切图 2.拼合(Sprites) 原始社会啊! 后来CSSGagagrunt-css-sprite 字体图标 相见不曾相识 Emoji绘文字 iconfont.cn直 ...
- Linux Shell 程序调试
Linux Shell 程序调试 Shell程序的调试是通过运行程序时加入相关调试选项或在脚本程序中加入相关语句,让shell程序在执行过程中显示出一些可供参考的“调试信息”.当然,用户也可以在she ...
- 【NOI2017】游戏 2-sat算法
[题目]LibreOJ [题意]n场游戏,有三种车ABC,给定长度为n的字符串,'a'表示不能选A,'b''c'同理,'x'表示不限,至多d个'x'.有m个限制(i,hi,j,hj)表示如果第i场选择 ...
- nmon的安装和使用
1.下载nmon https://zh.osdn.net/projects/sfnet_nmon/downloads/nmon_x86_64_rhel6/ 2../nmon_x86_64_rhel6 ...
- 选择问题(选择数组中第K小的数)
由排序问题可以引申出选择问题,选择问题就是选择并返回数组中第k小的数,如果把数组全部排好序,在返回第k小的数,也能正确返回,但是这无疑做了很多无用功,由上篇博客中提到的快速排序,稍稍修改下就可以以较小 ...
- caffe Python API 之中值转换
# 编写一个函数,将二进制的均值转换为python的均值 def convert_mean(binMean,npyMean): blob = caffe.proto.caffe_pb2.BlobPro ...
- ovirt系统磁盘删除后清理功能验证步骤
测试步骤主要是针对ovirt系统磁盘的‘删除后清理’功能,如下图所示: 测试如下两种方式: 预置条件: 搭建iscsi服务器,且划分一个11G的盘 勾选删除后清理操作步骤:1 .在linux虚拟机 d ...
- selenium grid应用1-多浏览器执行用例
driver =webdriver.Remote(command_executor=’http://127.0.0.1:4444/wd/hub’, desired_capabilities=Desir ...