package com.wyj.excel.test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
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 com.wyj.annotation.ExcelAnnotation;
import com.wyj.bo.InsuranceCosts;
import com.wyj.bo.Statistics;
import com.wyj.utils.StringUtils;
/**
* 导入excel的模板类
*
* @author 王宜君
*
*/
public class ImportExcel
{
private Class classzz;
public ImportExcel( Class classzz )
{
this.classzz = classzz;
}
/**
* 导入excel
*
* @param file
* @param pattern
* @return
*/
public Collection importExcel( InputStream in, String... pattern )
{
Collection list = new ArrayList();
try
{
/*
* 类反射得到调用方法
*/
// 得到目标类的所有字段列表
Field[] field = classzz.getDeclaredFields();
// 将所有标有annotation的字段,也就是允许导入数据的字段,放入到一个中
Map fieldMap = new HashMap();
// 循环读取所有字段
for ( int i = 0; i < field.length; i++ )
{
Field f = field[i];
// 得到单个字段上的Annotation
ExcelAnnotation excelAnnotation = f.getAnnotation( ExcelAnnotation.class );
// 如果标识了Annotation的话
if ( null != excelAnnotation )
{
// 构造设置了Annotation的字段的setter方法
String fieldName = f.getName();
String setMethodName = "set"
+ fieldName.substring( 0, 1 ).toUpperCase()
+ fieldName.substring( 1 );
// 构造调用的method
Method method = classzz.getMethod( setMethodName,
new Class[] {f.getType()} );
// 将这个method以annotation的名字为key来存入
fieldMap.put( excelAnnotation.exportName(), method );
}
}
/*
* excel的解析开始
*/
// 得到工作表
HSSFWorkbook book = new HSSFWorkbook( in );
// 得到第一页
HSSFSheet sheet = book.getSheetAt( 0 );
// 得到第一面的所有行
Iterator row = sheet.rowIterator();
/*
* 标题解析
*/
// 得到第一行,也就是标题行
Row title = row.next();
// 得到第一行的所有列
Iterator cellTitle = title.cellIterator();
// 将标题的文字内容放入到一个map中
Map titleMap = new HashMap();
// 从标题的第一列开始
int i = 0;
// 循环所有的列
while ( cellTitle.hasNext() )
{
Cell cell = cellTitle.next();
String value = cell.getStringCellValue();
titleMap.put( i, value );
i++;
}
/*
* 解析内容行
*/
// 用来格式化日期的DateFormat
SimpleDateFormat sf;
if ( pattern.length < 1 )
{
sf = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
} else
sf = new SimpleDateFormat( pattern[0] );
while ( row.hasNext() )
{
// 标题下的第一行
Row rown = row.next();
// 行的所有列
Iterator cellBody = rown.cellIterator();
// 得到传入类的实例
T tObject = classzz.newInstance();
int k = 0;
// 遍历一行的列
while ( cellBody.hasNext() )
{
Cell cell = cellBody.next();
// 这里得到此列对应的标题
String titleString = (String)titleMap.get( k );
// 如果这一列的标题和类中的某一列的Annotation相同,那么则调用此类的setter方法,进行设值
if ( fieldMap.containsKey( titleString ) )
{
Method setMethod = (Method)fieldMap.get( titleString );
// 得到setter方法的参数
Type[] ts = setMethod.getGenericParameterTypes();
// 只要一个参数
String xClass = ts[0].toString();
// 判断参数类型
if ( xClass.equals( "class java.lang.String" ) )
{
setMethod.invoke( tObject, cell
.getStringCellValue() );
} else if ( xClass.equals( "class java.util.Calendar" ) )
{
Calendar c = new GregorianCalendar();
Date d = sf.parse( cell.getStringCellValue() );
c.setTime( d );
setMethod.invoke( tObject, c );
} else if ( xClass.equals( "class java.util.Date" ) )
{
Date d = StringUtils.getTextDate( cell
.getStringCellValue(), "yyyy-MM-dd" );
setMethod.invoke( tObject, d );
} else if ( xClass.equals( "class java.lang.Boolean" ) )
{
Boolean boolName = true;
if ( cell.getStringCellValue().equals( "否" ) )
{
boolName = false;
}
setMethod.invoke( tObject, boolName );
} else if ( xClass.equals( "class java.lang.Integer" ) )
{
setMethod.invoke( tObject, new Integer( cell
.getStringCellValue() ) );
} else if ( xClass.equals( "class java.lang.Long" ) )
{
setMethod.invoke( tObject, new Long( cell
.getStringCellValue() ) );
} else if ( xClass.equals( "class java.lang.Double" ) )
{
setMethod.invoke( tObject, new Double( cell
.getNumericCellValue() ) );
}
}
// 下一列
k++;
}
list.add( tObject );
}
} catch ( Exception e )
{
e.printStackTrace();
return null;
}
return list;
}
public static void main( String[] args ) throws FileNotFoundException
{
ImportExcel insuranceCostsExcel = new ImportExcel(
InsuranceCosts.class );
ImportExcel statisticsExcel = new ImportExcel(
Statistics.class );
File insuranceCostsFile = new File(
"file\\excel\\exportInsuranceCosts.xls" );
File statisticsFile = new File( "file\\excel\\exportStatistics.xls" );
Long befor = System.currentTimeMillis();
final List insuranceCostsResult = (ArrayList)insuranceCostsExcel.importExcel( new FileInputStream( insuranceCostsFile ) );
Long after = System.currentTimeMillis();
System.out.println( "此次操作共耗时:" + (after - befor) );
final List statisticsResult =(ArrayList)statisticsExcel.importExcel( new FileInputStream( statisticsFile ) );
printInsuranceCosts( insuranceCostsResult );
printStatistics( statisticsResult );
}
/**
* 得到文件的扩展名 <功能详细描述>
*
* @param file
* 文件
* @return [参数说明]
* @return String [返回类型说明]
* @exception throws
* [违例类型] [违例说明]
* @see [类、类#方法、类#成员]
*/
public static String getExtension( File file )
{
String fileName = file.getName();
String extension = fileName.lastIndexOf( "." ) == -1 ? "" : fileName
.substring( fileName.lastIndexOf( "." ) + 1 );
return extension;
}
public static void printInsuranceCosts( final List insuranceCostsResult )
{
new Thread()
{
public void run()
{
for ( int i = 0; i < insuranceCostsResult.size(); i++ )
{
InsuranceCosts insuranceCosts = (InsuranceCosts)insuranceCostsResult.get( i );
System.out.println( "导入的信息为:"+insuranceCosts.getInsuranceId()
+ ","
+ insuranceCosts.getInsuranceTypeId()
+ ","
+ insuranceCosts.getVehicleNo()
+ ","
+ insuranceCosts.getInsuranceCompany()
+ ","
+ insuranceCosts.getInsuranceType()
+ ","
+ insuranceCosts.getContecter()
+ ","
+ insuranceCosts.getPhone()
+ ","
+ insuranceCosts.getMoney()
+ ","
+ insuranceCosts.getUsetax()
+ ","
+ StringUtils.getTextDateStr( insuranceCosts
.getBuyDate(), "yyyy-MM-dd" )
+ ","
+ StringUtils.getTextDateStr( insuranceCosts
.getEndDate(), "yyyy-MM-dd" ) + ","
+ insuranceCosts.getImg() );
}
};
}.start();
}
public static void printStatistics( final List statisticsResult )
{
new Thread()
{
public void run()
{
for ( int i = 0; i < statisticsResult.size(); i++ )
{
Statistics statistics = (Statistics)statisticsResult.get( i );
System.out.println( "导入的信息为:"+statistics.getName()+","+statistics.getType()+","+statistics.getVendor()+","+statistics.getSubtype());
}
};
}.start();
}
}
| |
excel的注解类
package com.wyj.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ExcelAnnotation
{
String exportName() default "";
}
excel注解的实体类
package com.wyj.bo;
import java.util.Date;
import com.wyj.annotation.ExcelAnnotation;
/**
* 保险费用实体类 <功能详细描述>
*
* @author 王宜君
* @version [版本号, Mar 24, 2013]
* @see [相关类/方法]
* @since [产品/模块版本]
*/
public class InsuranceCosts
{
@ExcelAnnotation(exportName="insuranceId")
private String insuranceId;// 保单号码
@ExcelAnnotation(exportName="insuranceTypeId")
private String insuranceTypeId;// 保险种类id
@ExcelAnnotation(exportName="vehicleNo")
private String vehicleNo;// 车牌号码
@ExcelAnnotation(exportName="insuranceCompany")
private String insuranceCompany;// 保险公司
@ExcelAnnotation(exportName="insuranceType")
private String insuranceType;// 保险类型
@ExcelAnnotation(exportName="contecter")
private String contecter;// 联系人
@ExcelAnnotation(exportName="phone")
private String phone;// 电话
@ExcelAnnotation(exportName="money")
private Double money;// 保险金额
@ExcelAnnotation(exportName="usetax")
private Double usetax;// 使用税
@ExcelAnnotation(exportName="buyDate")
private Date buyDate;// 购置日期
@ExcelAnnotation(exportName="endDate")
private Date endDate;// 到期日期
@ExcelAnnotation(exportName="img")
private String img;// 保险图片路径
// Constructors
public String getInsuranceId()
{
return insuranceId;
}
public void setInsuranceId( String insuranceId )
{
this.insuranceId = insuranceId;
}
public String getInsuranceTypeId()
{
return insuranceTypeId;
}
public void setInsuranceTypeId( String insuranceTypeId )
{
this.insuranceTypeId = insuranceTypeId;
}
/** default constructor */
public InsuranceCosts()
{
}
/** full constructor */
public InsuranceCosts( InsuranceCostsId id,String vehicleNo,
String insuranceCompany,String insuranceType,String contecter,
String phone,Double money,Double usetax,Date buyDate,Date endDate,
String img )
{
this.vehicleNo = vehicleNo;
this.insuranceCompany = insuranceCompany;
this.insuranceType = insuranceType;
this.contecter = contecter;
this.phone = phone;
this.money = money;
this.usetax = usetax;
this.buyDate = buyDate;
this.endDate = endDate;
this.img = img;
}
// Property accessors
public String getVehicleNo()
{
return this.vehicleNo;
}
public void setVehicleNo( String vehicleNo )
{
this.vehicleNo = vehicleNo;
}
public String getInsuranceCompany()
{
return this.insuranceCompany;
}
public void setInsuranceCompany( String insuranceCompany )
{
this.insuranceCompany = insuranceCompany;
}
public String getInsuranceType()
{
return this.insuranceType;
}
public void setInsuranceType( String insuranceType )
{
this.insuranceType = insuranceType;
}
public String getContecter()
{
return this.contecter;
}
public void setContecter( String contecter )
{
this.contecter = contecter;
}
public String getPhone()
{
return this.phone;
}
public void setPhone( String phone )
{
this.phone = phone;
}
public Double getMoney()
{
return this.money;
}
public void setMoney( Double money )
{
this.money = money;
}
public Double getUsetax()
{
return this.usetax;
}
public void setUsetax( Double usetax )
{
this.usetax = usetax;
}
public Date getBuyDate()
{
return this.buyDate;
}
public void setBuyDate( Date buyDate )
{
this.buyDate = buyDate;
}
public Date getEndDate()
{
return this.endDate;
}
public void setEndDate( Date endDate )
{
this.endDate = endDate;
}
public String getImg()
{
return this.img;
}
public void setImg( String img )
{
this.img = img;
}
/*
public Class extends Annotation> annotationType()
{
// TODO Auto-generated method stub
return null;
}*/
}