package test.excelTest;

 import java.io.File;
import java.io.FileInputStream;
import java.lang.reflect.Field;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List; import org.apache.commons.lang.StringUtils;
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.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.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 org.slf4j.Logger;
import org.slf4j.LoggerFactory; /**
* Desc:文件工具类
*/
public class FileUtil {
private static Logger logger = LoggerFactory
.getLogger(FileUtil.class); /**
* 读取xml
* @param classz
* @param fileSrc
* @return
*/
public static Object readExcel(Class classz,String fileSrc){
List list = new ArrayList<>();
int x = 0;//记录出错位置
int y = 0; try {
Workbook wb = null;
if (isExcel2003(fileSrc)){
wb = new HSSFWorkbook(new FileInputStream(new File(fileSrc)));
}else if(isExcel2007(fileSrc)){
wb = new XSSFWorkbook(new FileInputStream(new File(fileSrc)));
}
Sheet sheet = wb.getSheetAt(0); if(sheet.getLastRowNum() < 1){
return list;
} Row headRow = sheet.getRow(0); for (int i = 1; i < sheet.getLastRowNum() + 1 ; i++){
x = i;
Row row = sheet.getRow(i);
Object t = classz.newInstance(); for(int j = 0; j < row.getLastCellNum(); j++){
y = j;
Cell cellHeadFiled = headRow.getCell(j);
Cell cellFiled = row.getCell(j);
if(cellHeadFiled == null || cellFiled == null){
continue;
} String cellFiledName = null;
if(cellHeadFiled != null){
cellFiledName = cellHeadFiled.getRichStringCellValue().getString();
} cellFiled.setCellType(Cell.CELL_TYPE_STRING);
String cellFiledValue = String.valueOf(cellFiled.getRichStringCellValue()); setFiledValue(t, cellFiledName, cellFiledValue, x, y);
} list.add(t);
}
} catch (Exception e) {
e.printStackTrace();
logger.error("解析excel异常。请检查文件内容是否正确,第"+y+"行,"+(x+1)+"列出错");;
} return list;
} /**
* 设置字段值
* @param object
* @param excelFiledName
* @param value
*/
private static void setFiledValue(Object object,String excelFiledName,String value, int x, int y){
Class classz = object.getClass();
Field[] fields = classz.getDeclaredFields(); for(Field field : fields){
String filedName = field.getName();
ExcelField excelField = field.getAnnotation(ExcelField.class);
if(excelField != null){
filedName = excelField.fieldName();
} String orgFiledName = field.getType().getName();
String filedTypeName = orgFiledName.toUpperCase(); if(excelFiledName.equalsIgnoreCase(filedName)){
field.setAccessible(true);
try {
if(isNumeric(value)){
NumberFormat numberFormat = NumberFormat.getNumberInstance();
Number number = numberFormat.parse(value); if(filedTypeName.contains("INT")){
field.set(object, number.intValue());
}else if(filedTypeName.contains("DOUBLE")){
field.set(object, number.doubleValue());
}else if(filedTypeName.contains("FLOAT")){
field.set(object, number.floatValue());
}else if(filedTypeName.contains("LONG")){
field.set(object, number.longValue());
}else if(filedTypeName.contains("SHORT")){
field.set(object, number.shortValue());
}
}else {
if(filedTypeName.contains("BOOLEAN")){
field.set(object,Boolean.valueOf(value));
}else{
field.set(object,value);
}
} } catch (Exception e) {
e.printStackTrace();
logger.error("暂不支持的数据类型["+orgFiledName+"]。请检查文件内容是否正确,第"+y+"行,"+(x+1)+"列出错");
}
break;
}
}
} /**
* 判断字符串是否为数字
* @param str
* @return
*/
public static boolean isNumeric(String str){
if(StringUtils.isEmpty(str)){
return false;
} for (int i = str.length();--i>=0;){
if (!Character.isDigit(str.charAt(i))){
return false;
}
}
return true;
} public static boolean isExcel2003(String filePath)
{ return filePath.matches("^.+\\.(?i)(xls)$"); }
public static boolean isExcel2007(String filePath)
{ return filePath.matches("^.+\\.(?i)(xlsx)$"); } public static void main(String[] args) throws Exception {
String sre = "D://b.xls";
Object result = readExcel(Person.class, sre);
List<Person> list = (List<Person>) result;
for(Person person : list){
System.out.println("姓名:"+person.getName()+"---年龄:"+person.getAge()+"---性别:"+person.getSex());
} } }
 package test.excelTest;

 import java.lang.annotation.*;  

 /**
* Desc:Excel字段名
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ExcelField { public String fieldName();
}
 package test.excelTest;

 /**
* Desc: module
*/
public class Person { @ExcelField(fieldName="名字")
private String name; @ExcelField(fieldName="年龄")
private double age; @ExcelField(fieldName="性别")
private String sex; public Person(){ } public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public double getAge() {
return age;
} public void setAge(double age) {
this.age = age;
} public String getSex() {
return sex;
} public void setSex(String sex) {
this.sex = sex;
}
}

最新文章

  1. 基于注解的bean配置
  2. ctargs使用
  3. Unity5版本的AssetBundle打包方案之打包Scene场景
  4. adb_常用命令
  5. C与Python变量的区别
  6. 快逸报表部署 (一)-- demo连接mysql数据库
  7. 上海洋码头(www.ymatou.com)急招技术人才(职位:互联网软件开发工程师,.NET网站架构师,Web前端开发工程师,高级测试工程师,产品经理)
  8. oracle常见小问题解答ORA-01008,ORA-01036
  9. 共享锁(S锁)和排它锁(X锁)
  10. 使用asp.net动态添加html元素
  11. Ajax概述
  12. Register/unregister a dll to GAC
  13. shell 水平测试
  14. Python笔记5(字符串)-20160921
  15. C++中复制构造函数和赋值操作符
  16. vm lxc
  17. NodeJS 框架一览
  18. LeetCode(40)-Merge Sorted Array
  19. First Show
  20. Expression基础体验

热门文章

  1. 一个.java文件内只能写一个class吗
  2. oracle 数据导到 sql server
  3. CVE-2014-1767
  4. 题解 P1379 【八数码难题】
  5. C# 替换去除HTML标记方法(正则表达式)
  6. IOS版本判断
  7. 【dsu || 线段树合并】bzoj4756: [Usaco2017 Jan]Promotion Counting
  8. oracle如何保证读一致性 第二弹
  9. LeetCode(274)H-Index
  10. Erasing and Winning UVA - 11491 贪心