JAVA POI通用工具类文档格式.docx
《JAVA POI通用工具类文档格式.docx》由会员分享,可在线阅读,更多相关《JAVA POI通用工具类文档格式.docx(20页珍藏版)》请在冰豆网上搜索。
/**
*@MethodName:
listToExcel
*@Description:
导出Excel(可以导出到本地文件系统,也可以导出到浏览器,可自定义工作表大小)
*@paramlist数据源
*@paramfieldMap类的英文属性和Excel中的中文列名的对应关系
*如果需要的是引用对象的属性,则英文属性使用类似于EL表达式的格式
*如:
list中存放的都是student,student中又有college属性,而我们需要学院名称,则可以这样写
*fieldMap.put("
college.collegeName"
"
学院名称"
)
*@paramsheetName工作表的名称
*@paramsheetSize每个工作表中记录的最大个数
*@paramout导出流
*@throwsExcelException
publicstatic<
T>
voidlistToExcel(
List<
list,
LinkedHashMap<
String,String>
fieldMap,
StringsheetName,
intsheetSize,
OutputStreamout
)throwsExcelException{
if(list.size()==0||list==null){
thrownewExcelException("
数据源中没有任何数据"
);
if(sheetSize>
65535||sheetSize<
1){
sheetSize=65535;
//创建工作簿并发送到OutputStream指定的地方
WritableWorkbookwwb;
try{
wwb=Workbook.createWorkbook(out);
//因为2003的Excel一个工作表最多可以有65536条记录,除去列头剩下65535条
//所以如果记录太多,需要放到多个工作表中,其实就是个分页的过程
//1.计算一共有多少个工作表
doublesheetNum=Math.ceil(list.size()/newInteger(sheetSize).doubleValue());
//2.创建相应的工作表,并向其中填充数据
for(inti=0;
i<
sheetNum;
i++){
//如果只有一个工作表的情况
if(1==sheetNum){
WritableSheetsheet=wwb.createSheet(sheetName,i);
fillSheet(sheet,list,fieldMap,0,list.size()-1);
//有多个工作表的情况
}else{
WritableSheetsheet=wwb.createSheet(sheetName+(i+1),i);
//获取开始索引和结束索引
intfirstIndex=i*sheetSize;
intlastIndex=(i+1)*sheetSize-1>
list.size()-1?
list.size()-1:
(i+1)*sheetSize-1;
//填充工作表
fillSheet(sheet,list,fieldMap,firstIndex,lastIndex);
wwb.write();
wwb.close();
}catch(Exceptione){
e.printStackTrace();
//如果是ExcelException,则直接抛出
if(einstanceofExcelException){
throw(ExcelException)e;
//否则将其它异常包装成ExcelException再抛出
导出Excel失败"
导出Excel(可以导出到本地文件系统,也可以导出到浏览器,工作表大小为2003支持的最大值)
*@paramout导出流
)throwsExcelException{
listToExcel(list,fieldMap,sheetName,65535,out);
导出Excel(导出到浏览器,可以自定义工作表的大小)
*@paramresponse使用response可以导出到浏览器
HttpServletResponseresponse
//设置默认文件名为当前时间:
年月日时分秒
StringfileName=newSimpleDateFormat("
yyyyMMddhhmmss"
).format(newDate()).toString();
//设置response头信息
response.reset();
response.setContentType("
application/vnd.ms-excel"
//改成输出excel文件
response.setHeader("
Content-disposition"
attachment;
filename="
+fileName+"
.xls"
);
//创建工作簿并发送到浏览器
OutputStreamout=response.getOutputStream();
listToExcel(list,fieldMap,sheetName,sheetSize,out);
}catch(Exceptione){
导出Excel(导出到浏览器,工作表的大小是2003支持的最大值)
listToExcel(list,fieldMap,sheetName,65535,response);
excelToList
将Excel转化为List
*@paramin:
承载着Excel的输入流
*@paramsheetIndex:
要导入的工作表序号
*@paramentityClass:
List中对象的类型(Excel中的每一行都要转化为该类型的对象)
*@paramfieldMap:
Excel中的中文列头和类的英文属性的对应关系Map
*@paramuniqueFields:
指定业务主键组合(即复合主键),这些列的组合不能重复
*@return:
List
excelToList(
InputStreamin,
Class<
entityClass,
String,String>
String[]uniqueFields
//定义要返回的list
resultList=newArrayList<
();
//根据Excel数据源创建WorkBook
Workbookwb=Workbook.getWorkbook(in);
//获取工作表
Sheetsheet=wb.getSheet(sheetName);
//获取工作表的有效行数
intrealRows=0;
for(inti=0;
i<
sheet.getRows();
i++){
intnullCols=0;
for(intj=0;
j<
sheet.getColumns();
j++){
CellcurrentCell=sheet.getCell(j,i);
if(currentCell==null||"
"
.equals(currentCell.getContents().toString())){
nullCols++;
if(nullCols==sheet.getColumns()){
break;
realRows++;
//如果Excel中没有数据则提示错误
if(realRows<
=1){
Excel文件中没有任何数据"
Cell[]firstRow=sheet.getRow(0);
String[]excelFieldNames=newString[firstRow.length];
//获取Excel中的列名
firstRow.length;
excelFieldNames[i]=firstRow[i].getContents().toString().trim();
//判断需要的字段在Excel中是否都存在
booleanisExist=true;
String>
excelFieldList=Arrays.asList(excelFieldNames);
for(StringcnName:
fieldMap.keySet()){
if(!
excelFieldList.contains(cnName)){
isExist=false;
break;
//如果有列名不存在,则抛出异常,提示错误
isExist){
Excel中缺少必要的字段,或字段名称有误"
//将列名和列号放入Map中,这样通过列名就可以拿到列号
String,Integer>
colMap=newLinkedHashMap<
excelFieldNames.length;
colMap.put(excelFieldNames[i],firstRow[i].getColumn());
}
//判断是否有重复行
//1.获取uniqueFields指定的列
Cell[][]uniqueCells=newCell[uniqueFields.length][];
uniqueFields.length;
intcol=colMap.get(uniqueFields[i]);
uniqueCells[i]=sheet.getColumn(col);
//2.从指定列中寻找重复行
for(inti=1;
realRows;
StringcurrentContent=uniqueCells[j][i].getContents();
CellsameCell=sheet.findCell(currentContent,
uniqueCells[j][i].getColumn(),
uniqueCells[j][i].getRow()+1,
uniqueCells[j][i].getColumn(),
uniqueCells[j][realRows-1].getRow(),
true);
if(sameCell!
=null){
if(nullCols==uniqueFields.length){
thrownewExcelException("
Excel中有重复行,请检查"
//将sheet转换为list
//新建要转换的对象
Tentity=entityClass.newInstance();
//给对象中的字段赋值
for(Entry<
entry:
fieldMap.entrySet()){
//获取中文字段名
StringcnNormalName=entry.getKey();
//获取英文字段名
StringenNormalName=entry.getValue();
//根据中文字段名获取列号
intcol=colMap.get(cnNormalName);
//获取当前单元格中的内容
Stringcontent=sheet.getCell(col,i).getContents().toString().trim();
//给对象赋值
setFieldValueByName(enNormalName,content,entity);
resultList.add(entity);
}catch(Exceptione){
导入Excel失败"
returnresultList;
/*<
-------------------------辅助的私有方法----------------------------------------------->
*/
getFieldValueByName
根据字段名获取字段值
*@paramfieldName字段名
*@paramo对象
*@return字段值
privatestaticObjectgetFieldValueByName(StringfieldName,Objecto)throwsException{
Objectvalue=null;
Fieldfield=getFieldByName(fieldName,o.getClass());
if(field!
field.setAccessible(true);
value=field.get(o);
thrownewExcelException(o.getClass().getSimpleName()+"
类不存在字段名"
+fieldName);
returnvalue;
getFieldByName
根据字段名获取字段
*@paramclazz包含该字段的类
*@return字段
privatestaticFieldgetFieldByName(StringfieldName,Class<
?
>
clazz){
//拿到本类的所有字段
Field[]selfFields=clazz.getDeclaredFields();
//如果本类中存在该字段,则返回
for(Fieldfield:
selfFields){
if(field.getName().equals(fieldName)){
returnfield;
//否则,查看父类中是否存在此字段,如果有则返回
superClazz=clazz.getSuperclass();
if(superClazz!
=null&
&
superClazz!
=Object.class){
returngetFieldByName(fieldName,superClazz);
//如果本类和父类都没有,则返回空
returnnull;
getFieldValueByNameSequence
*根据带路径或不带路径的属性名获取属性值
*即接受简单属性名,如userName等,又接受带路径的属性名,如student.department.name等
*
*@paramfieldNameSequence带路径的属性名或简单属性名
*@return属性值
*@throwsException
privatestaticObjectgetFieldValueByNameSequence(StringfieldNameSequence,Objecto)throwsException{
//将fieldNameSequence进行拆分
String[]attributes=fieldNameSequence.split("
\\."
if(attributes.length==1){
value=getFieldValueByName(fieldNameSequence,o);
//根据属性名获取属性对象
ObjectfieldObj=getFieldValueByName(attributes[0],o);
StringsubFieldNameSequence=fieldNameSequence.substring(fieldNam