主要涉及技术,注解和反射
过程1、创建Excel数据实体类
在
实体类的属性上面添加注解,对应Excel表中的title
2、获取Excel数据(用到IO流)
3、将数据通过反射和注解封装到实体类中 (重点和难点)
private static Map<Integer,String> Y_TITLE_MAP=new HashMap<Integer,String>();
/**
* 读取excel并封装为对象
* 将第二行中的纵坐标和title存入Map中
*
* @param path
* @throws FileNotFoundException
*/
private static void init_Y_TITLE_MAP(HSSFWorkbook hSSFWorkbook){
HSSFSheet sheet = hSSFWorkbook.getSheetAt(0);
HSSFRow row = sheet.getRow(1);
System.out.println("###############");
for (int y = 0; y < row.getLastCellNum(); y++) {// 循环单元格
try {
String data = getCellFormatValue(row.getCell(y)).trim();
System.out.println( y+ data);
Y_TITLE_MAP.put(y, data);
} catch (Exception e) {
// System.out.println(new Date() + "j=" + j);
e.printStackTrace();
}
} System.out.println("###############");
}
* 读取excel并封装为对象
* 将第二行中的纵坐标和title存入Map中
*
* @param path
* @throws FileNotFoundException
*/
private static void init_Y_TITLE_MAP(HSSFWorkbook hSSFWorkbook){
HSSFSheet sheet = hSSFWorkbook.getSheetAt(0);
HSSFRow row = sheet.getRow(1);
System.out.println("###############");
for (int y = 0; y < row.getLastCellNum(); y++) {// 循环单元格
try {
String data = getCellFormatValue(row.getCell(y)).trim();
System.out.println( y+ data);
Y_TITLE_MAP.put(y, data);
} catch (Exception e) {
// System.out.println(new Date() + "j=" + j);
e.printStackTrace();
}
} System.out.println("###############");
}
/**
* 读取excel并封装为对象
*
* @param path
* @throws FileNotFoundException
*/
public static List<PeopleInfo > readExcel2Object(String path)
throws FileNotFoundException {
List<PeopleInfo > list = new ArrayList<PeopleInfo >();
POIFSFileSystem pOIFSFileSystem = null;
HSSFWorkbook hSSFWorkbook = null;
HSSFSheet sheet = null;
HSSFRow row = null;
InputStream is = new FileInputStream(path);
try {
pOIFSFileSystem = new POIFSFileSystem(is);
hSSFWorkbook = new HSSFWorkbook(pOIFSFileSystem);
} catch (IOException e) {
e.printStackTrace();
}
init_Y_TITLE_MAP(hSSFWorkbook);//
int sum = 0;
// StringBuilder phones = new StringBuilder();
;
for (int s = 0; s < 1; s++) {// wb.getNumberOfSheets()
sheet = hSSFWorkbook.getSheetAt(s);
if (null == sheet)
continue;
// 得到总行数
int rowNum = sheet.getLastRowNum();
int init_i=2;
for (int i = init_i; i <= rowNum; i++) {// 循环行数
ExcelData ed=new ExcelData();
row = sheet.getRow(i);
if(null==row){
// System.out.println("行位null"+(i+1));
break;
}else{
}
* 读取excel并封装为对象
*
* @param path
* @throws FileNotFoundException
*/
public static List<PeopleInfo > readExcel2Object(String path)
throws FileNotFoundException {
List<PeopleInfo > list = new ArrayList<PeopleInfo >();
POIFSFileSystem pOIFSFileSystem = null;
HSSFWorkbook hSSFWorkbook = null;
HSSFSheet sheet = null;
HSSFRow row = null;
InputStream is = new FileInputStream(path);
try {
pOIFSFileSystem = new POIFSFileSystem(is);
hSSFWorkbook = new HSSFWorkbook(pOIFSFileSystem);
} catch (IOException e) {
e.printStackTrace();
}
init_Y_TITLE_MAP(hSSFWorkbook);//
int sum = 0;
// StringBuilder phones = new StringBuilder();
;
for (int s = 0; s < 1; s++) {// wb.getNumberOfSheets()
sheet = hSSFWorkbook.getSheetAt(s);
if (null == sheet)
continue;
// 得到总行数
int rowNum = sheet.getLastRowNum();
int init_i=2;
for (int i = init_i; i <= rowNum; i++) {// 循环行数
ExcelData ed=new ExcelData();
row = sheet.getRow(i);
if(null==row){
// System.out.println("行位null"+(i+1));
break;
}else{
}
PeopleInfo peopleInfo = new PeopleInfo();
int lastCellNum=row.getLastCellNum();
// System.out.println(lastCellNum);
for (int y = 0; y < lastCellNum; y++) {// 循环单元格
try {
String data = getCellFormatValue(row.getCell(y)).trim();
if(StringUtils.isBlank(data)) continue;
String cnTitle=Y_TITLE_MAP.get(y);
if(y<=18){//基本信息
int lastCellNum=row.getLastCellNum();
// System.out.println(lastCellNum);
for (int y = 0; y < lastCellNum; y++) {// 循环单元格
try {
String data = getCellFormatValue(row.getCell(y)).trim();
if(StringUtils.isBlank(data)) continue;
String cnTitle=Y_TITLE_MAP.get(y);
if(y<=18){//基本信息
setField(peopleInfo,cnTitle, data);//通过查到的注解和实体类中的注解做对比,相同存入数据
}
} catch (Exception e) {
// System.out.println(new Date() + "j=" + j);
e.printStackTrace();
}
}//end of inner for
// System.out.println(new Date() + "j=" + j);
e.printStackTrace();
}
}//end of inner for
list.add(peopleInfo);
}
}
return list;
}
/**
* 根据HSSFCell类型设置数据
*
* @param cell
* @return
*/
private static String getCellFormatValue(HSSFCell cell) {
String cellvalue = "";
if (cell != null) {
// System.out.println("===" + cell.getCellType());
// 判断当前Cell的Type
switch (cell.getCellType()) {
// 如果当前Cell的Type为NUMERIC
case HSSFCell.CELL_TYPE_NUMERIC:
case HSSFCell.CELL_TYPE_FORMULA: {
// 判断当前的cell是否为Date
if (HSSFDateUtil.isCellDateFormatted(cell)) {
// 如果是Date类型,则转化为Data格式
// 方法1:这样子的data格式是带时分秒的:2011-10-12 0:00:00
// cellvalue = cell.getDateCellValue().toLocaleString();
// 方法2:这样子的data格式是不带带时分秒的:2011-10-12
Date date = cell.getDateCellValue();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
cellvalue = sdf.format(date);
}
// 如果是纯数字
else {
// 取得当前Cell的数值
// cellvalue = String.valueOf(cell.getNumericCellValue());
DecimalFormat df = new DecimalFormat("#");
cellvalue = df.format(cell.getNumericCellValue());
// System.out.println("type666=="+df.format(cell.getNumericCellValue()));
}
break;
}
// 如果当前Cell的Type为STRIN
case HSSFCell.CELL_TYPE_STRING:
// 取得当前的Cell字符串
cellvalue = cell.getRichStringCellValue().getString();
break;
// 默认的Cell值
default:
cellvalue = " ";
}
} else {
cellvalue = "";
}
return cellvalue;
}
* 根据HSSFCell类型设置数据
*
* @param cell
* @return
*/
private static String getCellFormatValue(HSSFCell cell) {
String cellvalue = "";
if (cell != null) {
// System.out.println("===" + cell.getCellType());
// 判断当前Cell的Type
switch (cell.getCellType()) {
// 如果当前Cell的Type为NUMERIC
case HSSFCell.CELL_TYPE_NUMERIC:
case HSSFCell.CELL_TYPE_FORMULA: {
// 判断当前的cell是否为Date
if (HSSFDateUtil.isCellDateFormatted(cell)) {
// 如果是Date类型,则转化为Data格式
// 方法1:这样子的data格式是带时分秒的:2011-10-12 0:00:00
// cellvalue = cell.getDateCellValue().toLocaleString();
// 方法2:这样子的data格式是不带带时分秒的:2011-10-12
Date date = cell.getDateCellValue();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
cellvalue = sdf.format(date);
}
// 如果是纯数字
else {
// 取得当前Cell的数值
// cellvalue = String.valueOf(cell.getNumericCellValue());
DecimalFormat df = new DecimalFormat("#");
cellvalue = df.format(cell.getNumericCellValue());
// System.out.println("type666=="+df.format(cell.getNumericCellValue()));
}
break;
}
// 如果当前Cell的Type为STRIN
case HSSFCell.CELL_TYPE_STRING:
// 取得当前的Cell字符串
cellvalue = cell.getRichStringCellValue().getString();
break;
// 默认的Cell值
default:
cellvalue = " ";
}
} else {
cellvalue = "";
}
return cellvalue;
}
public static void setField(Object object,String cnTitle,String data) throws Exception {
Class clazz=object.getClass();//反射机制的获取
Field [] fields=clazz.getDeclaredFields();//查出反射机制中所有属性
// System.out.println( " "+fields.length);
for(Field f:fields){//循环查找所有字段
// System.out.println( " "+f.getAnnotation(ExcelAnnotation.class));
ExcelAnnotation ea=f.getAnnotation(ExcelAnnotation.class);//查找自定义注解
if(null!=ea&&ea.title().equalsIgnoreCase(cnTitle.trim())){
// System.out.println( " "+ea.title());//输出自定义的注解
setField( object, f, data);
return;
}
}
throw new Exception("没有找到对应的属性:"+cnTitle);
}
Class clazz=object.getClass();//反射机制的获取
Field [] fields=clazz.getDeclaredFields();//查出反射机制中所有属性
// System.out.println( " "+fields.length);
for(Field f:fields){//循环查找所有字段
// System.out.println( " "+f.getAnnotation(ExcelAnnotation.class));
ExcelAnnotation ea=f.getAnnotation(ExcelAnnotation.class);//查找自定义注解
if(null!=ea&&ea.title().equalsIgnoreCase(cnTitle.trim())){
// System.out.println( " "+ea.title());//输出自定义的注解
setField( object, f, data);
return;
}
}
throw new Exception("没有找到对应的属性:"+cnTitle);
}
对获取的数据进行类型转换
public static void setField(Object object,Field f,String data) throws Exception {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
// Class clazz=object
f.setAccessible(true); //设置些属性是可以访问的
// System.out.println("name:"+f.getName()+"\t value = "+val);
String type = f.getType().toString();//得到此属性的类型
if (type.endsWith("String")) {
// System.out.println(f.getType()+"\t是String");
f.set(object,data) ; //给属性设值
}else if(type.endsWith("int") || type.endsWith("Integer")){
// System.out.println(f.getType()+"\t是int");
f.set(object,Integer.valueOf(data)) ; //给属性设值
}else if(type.endsWith("float") || type.endsWith("Float")){
// System.out.println(f.getType()+"\t是int");
f.set(object,Float.valueOf(data)) ; //给属性设值
}else if(type.endsWith("Date")){
// System.out.println(f.getType()+"\t是Date");
f.set(object, dateFormat.parse(data));
}
else{
// System.out.println(f.getType()+"\t");
throw new Exception("暂未实现,请实现");
}
}
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
// Class clazz=object
f.setAccessible(true); //设置些属性是可以访问的
// System.out.println("name:"+f.getName()+"\t value = "+val);
String type = f.getType().toString();//得到此属性的类型
if (type.endsWith("String")) {
// System.out.println(f.getType()+"\t是String");
f.set(object,data) ; //给属性设值
}else if(type.endsWith("int") || type.endsWith("Integer")){
// System.out.println(f.getType()+"\t是int");
f.set(object,Integer.valueOf(data)) ; //给属性设值
}else if(type.endsWith("float") || type.endsWith("Float")){
// System.out.println(f.getType()+"\t是int");
f.set(object,Float.valueOf(data)) ; //给属性设值
}else if(type.endsWith("Date")){
// System.out.println(f.getType()+"\t是Date");
f.set(object, dateFormat.parse(data));
}
else{
// System.out.println(f.getType()+"\t");
throw new Exception("暂未实现,请实现");
}
}
主函数调用
public static void main(String[] args) throws FileNotFoundException {
String path = "C:\\Users\\Administrator\\Desktop\\import_tpl.xls";
readExcel2Object(path);
readExcel2Object(path);
}
4、对数据存入数据库并进行操作
拿到数据后自己操作吧
这个方法会用到一些jar包,在网上可以找到类似的