




已阅读5页,还剩9页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
JAVA POI数据导入导出工具类1. Exception处理public class ExcelException extends Exception public ExcelException() / TODO Auto-generated constructor stub public ExcelException(String message) super(message); / TODO Auto-generated constructor stub public ExcelException(Throwable cause) super(cause); / TODO Auto-generated constructor stub public ExcelException(String message, Throwable cause) super(message, cause); / TODO Auto-generated constructor stub 2. POI核心处理/* * author : SUNZK-QQ:1131341075 * Date : 2018-8-23 下午9:13:21 * Comments : 导入导出Excel工具类 * Version : 1.0.0 */ public class ExcelUtil /* * MethodName : listToExcel * Description : 导出Excel(可以导出到本地文件系统,也可以导出到浏览器,可自定义工作表大小) * param list 数据源 * param fieldMap 类的英文属性和Excel中的中文列名的对应关系 * 如果需要的是引用对象的属性,则英文属性使用类似于EL表达式的格式 * 如:list中存放的都是student,student中又有college属性,而我们需要学院名称,则可以这样写 * fieldMap.put(college.collegeName,学院名称) * param sheetName 工作表的名称 * param sheetSize 每个工作表中记录的最大个数 * param out 导出流 * throws ExcelException */ public static void listToExcel ( List list , LinkedHashMap fieldMap, String sheetName, int sheetSize, OutputStream out ) throws ExcelException if(list.size()=0 | list=null) throw new ExcelException(数据源中没有任何数据); if(sheetSize65535 | sheetSize1) sheetSize=65535; /创建工作簿并发送到OutputStream指定的地方 WritableWorkbook wwb; try wwb = Workbook.createWorkbook(out); /因为2003的Excel一个工作表最多可以有65536条记录,除去列头剩下65535条 /所以如果记录太多,需要放到多个工作表中,其实就是个分页的过程 /1.计算一共有多少个工作表 double sheetNum=Math.ceil(list.size()/new Integer(sheetSize).doubleValue(); /2.创建相应的工作表,并向其中填充数据 for(int i=0; ilist.size()-1 ? list.size()-1 : (i+1)*sheetSize-1; /填充工作表 fillSheet(sheet, list, fieldMap, firstIndex, lastIndex); wwb.write(); wwb.close(); catch (Exception e) e.printStackTrace(); /如果是ExcelException,则直接抛出 if(e instanceof ExcelException) throw (ExcelException)e; /否则将其它异常包装成ExcelException再抛出 else throw new ExcelException(导出Excel失败); /* * MethodName : listToExcel * Description : 导出Excel(可以导出到本地文件系统,也可以导出到浏览器,工作表大小为2003支持的最大值) * param list 数据源 * param fieldMap 类的英文属性和Excel中的中文列名的对应关系 * param out 导出流 * throws ExcelException */ public static void listToExcel ( List list , LinkedHashMap fieldMap, String sheetName, OutputStream out ) throws ExcelException listToExcel(list, fieldMap, sheetName, 65535, out); /* * MethodName : listToExcel * Description : 导出Excel(导出到浏览器,可以自定义工作表的大小) * param list 数据源 * param fieldMap 类的英文属性和Excel中的中文列名的对应关系 * param sheetSize 每个工作表中记录的最大个数 * param response 使用response可以导出到浏览器 * throws ExcelException */ public static void listToExcel ( List list , LinkedHashMap fieldMap, String sheetName, int sheetSize, HttpServletResponse response ) throws ExcelException /设置默认文件名为当前时间:年月日时分秒 String fileName=new SimpleDateFormat(yyyyMMddhhmmss).format(new Date().toString(); /设置response头信息 response.reset(); response.setContentType(application/vnd.ms-excel); /改成输出excel文件 response.setHeader(Content-disposition,attachment; filename=+fileName+.xls ); /创建工作簿并发送到浏览器 try OutputStream out=response.getOutputStream(); listToExcel(list, fieldMap, sheetName, sheetSize,out ); catch (Exception e) e.printStackTrace(); /如果是ExcelException,则直接抛出 if(e instanceof ExcelException) throw (ExcelException)e; /否则将其它异常包装成ExcelException再抛出 else throw new ExcelException(导出Excel失败); /* * MethodName : listToExcel * Description : 导出Excel(导出到浏览器,工作表的大小是2003支持的最大值) * param list 数据源 * param fieldMap 类的英文属性和Excel中的中文列名的对应关系 * param response 使用response可以导出到浏览器 * throws ExcelException */ public static void listToExcel ( List list , LinkedHashMap fieldMap, String sheetName, HttpServletResponse response ) throws ExcelException listToExcel(list, fieldMap, sheetName, 65535, response); /* * MethodName : excelToList * Description : 将Excel转化为List * param in :承载着Excel的输入流 * param sheetIndex :要导入的工作表序号 * param entityClass :List中对象的类型(Excel中的每一行都要转化为该类型的对象) * param fieldMap :Excel中的中文列头和类的英文属性的对应关系Map * param uniqueFields :指定业务主键组合(即复合主键),这些列的组合不能重复 * return :List * throws ExcelException */ public static List excelToList( InputStream in, String sheetName, Class entityClass, LinkedHashMap fieldMap, String uniqueFields ) throws ExcelException /定义要返回的list List resultList=new ArrayList(); try /根据Excel数据源创建WorkBook Workbook wb=Workbook.getWorkbook(in); /获取工作表 Sheet sheet=wb.getSheet(sheetName); /获取工作表的有效行数 int realRows=0; for(int i=0;isheet.getRows();i+) int nullCols=0; for(int j=0;jsheet.getColumns();j+) Cell currentCell=sheet.getCell(j,i); if(currentCell=null | .equals(currentCell.getContents().toString() nullCols+; if(nullCols=sheet.getColumns() break; else realRows+; /如果Excel中没有数据则提示错误 if(realRows=1) throw new ExcelException(Excel文件中没有任何数据); Cell firstRow=sheet.getRow(0); String excelFieldNames=new StringfirstRow.length; /获取Excel中的列名 for(int i=0;ifirstRow.length;i+) excelFieldNamesi=firstRowi.getContents().toString().trim(); /判断需要的字段在Excel中是否都存在 boolean isExist=true; List excelFieldList=Arrays.asList(excelFieldNames); for(String cnName : fieldMap.keySet() if(!excelFieldList.contains(cnName) isExist=false; break; /如果有列名不存在,则抛出异常,提示错误 if(!isExist) throw new ExcelException(Excel中缺少必要的字段,或字段名称有误); /将列名和列号放入Map中,这样通过列名就可以拿到列号 LinkedHashMap colMap=new LinkedHashMap(); for(int i=0;iexcelFieldNames.length;i+) colMap.put(excelFieldNamesi, firstRowi.getColumn(); /判断是否有重复行 /1.获取uniqueFields指定的列 Cell uniqueCells=new CelluniqueFields.length; for(int i=0;iuniqueFields.length;i+) int col=colMap.get(uniqueFieldsi); uniqueCellsi=sheet.getColumn(col); /2.从指定列中寻找重复行 for(int i=1;irealRows;i+) int nullCols=0; for(int j=0;juniqueFields.length;j+) String currentContent=uniqueCellsji.getContents(); Cell sameCell=sheet.findCell(currentContent, uniqueCellsji.getColumn(), uniqueCellsji.getRow()+1, uniqueCellsji.getColumn(), uniqueCellsjrealRows-1.getRow(), true); if(sameCell!=null) nullCols+; if(nullCols=uniqueFields.length) throw new ExcelException(Excel中有重复行,请检查); /将sheet转换为list for(int i=1;irealRows;i+) /新建要转换的对象 T entity=entityClass.newInstance(); /给对象中的字段赋值 for(Entry entry : fieldMap.entrySet() /获取中文字段名 String cnNormalName=entry.getKey(); /获取英文字段名 String enNormalName=entry.getValue(); /根据中文字段名获取列号 int col=colMap.get(cnNormalName); /获取当前单元格中的内容 String content=sheet.getCell(col, i).getContents().toString().trim(); /给对象赋值 setFieldValueByName(enNormalName, content, entity); resultList.add(entity); catch(Exception e) e.printStackTrace(); /如果是ExcelException,则直接抛出 if(e instanceof ExcelException) throw (ExcelException)e; /否则将其它异常包装成ExcelException再抛出 else e.printStackTrace(); throw new ExcelException(导入Excel失败); return resultList; /*/ /* * MethodName : getFieldValueByName * Description : 根据字段名获取字段值 * param fieldName 字段名 * param o 对象 * return 字段值 */ private static Object getFieldValueByName(String fieldName, Object o) throws Exception Object value=null; Field field=getFieldByName(fieldName, o.getClass(); if(field !=null) field.setAccessible(true); value=field.get(o); else throw new ExcelException(o.getClass().getSimpleName() + 类不存在字段名 +fieldName); return value; /* * MethodName : getFieldByName * Description : 根据字段名获取字段 * param fieldName 字段名 * param clazz 包含该字段的类 * return 字段 */ private static Field getFieldByName(String fieldName, Class clazz) /拿到本类的所有字段 Field selfFields=clazz.getDeclaredFields(); /如果本类中存在该字段,则返回 for(Field field : selfFields) if(field.getName().equals(fieldName) return field; /否则,查看父类中是否存在此字段,如果有则返回 Class superClazz=clazz.getSuperclass(); if(superClazz!=null & superClazz !=Object.class) return getFieldByName(fieldName, superClazz); /如果本类和父类都没有,则返回空 return null; /* * MethodName : getFieldValueByNameSequence * Description : * 根据带路径或不带路径的属性名获取属性值 * 即接受简单属性名,如userName等,又接受带路径的属性名,如等 * * param fieldNameSequence 带路径的属性名或简单属性名 * param o 对象 * return 属性值 * throws Exception */ private static Object getFieldValueByNameSequence(String fieldNameSequence, Object o) throws Exception Object value=null; /将fieldNameSequence进行拆分 String attributes=fieldNameSequence.split(.); if(attributes.length=1) value=getFieldValueByName(fieldNameSequence, o); else /根据属性名获取属性对象 Object fieldObj=getFieldValueByName(attributes0, o); String subFieldNameSequence=fieldNameSequence.substring(fieldNameSequence.indexOf(.)+1); value=getFieldValueByNameSequence(subFieldNameSequence, fieldObj); return value; /* * MethodName : setFieldValueByName * Description : 根据字段名给对象的字段赋值 * param fieldName 字段名 * param fieldValue 字段值 * param o 对象 */ private static void setFieldValueByName(String fieldName,Object fieldValue,Object o) throws Exception Field field=getFieldByName(fieldName, o.getClass(); if(field!=null) field.setAccessible(true); /获取字段类型 Class fieldType = field.getType(); /根据字段类型给字段赋值 if (String.class = fieldType) field.set(o, String.valueOf(fieldValue); else if (Integer.TYPE = fieldType) | (Integer.class = fieldType) field.set(o, Integer.parseInt(fieldValue.toString(); else if (Long.TYPE = fieldType) | (Long.class = fieldType) field.set(o, Long.valueOf(fieldValue.toString(); else if (Float.TYPE = fieldType) | (Float.class = fieldType) field.set(o, Float.valueOf(fieldValue.toString(); else if (Short.TYPE = fieldType) | (Short.class = fieldType) field.set(o, Short.valueOf(fieldValue.toString(); else if (Double.TYPE = fieldType) | (Double.class = fieldType) field.set(o, Double.valueOf(fieldValue.toString(); else if (Character.TYPE = fieldType) if (fieldValue!= null) & (fieldValue.toString().length() 0) field.set(o, Character .valueOf(fieldValue.toString().charAt(0); else if(Date.class=fieldType) field.set(o, new SimpleDateFormat(yyyy-MM-dd HH:mm:ss).parse(fieldValue.toString(); else field.set(o, fieldValue); else throw new ExcelException(o.getClass().getSimpleName() + 类不存在字段名 +fieldName); /* * MethodName : setColumnAutoSize * Description : 设置工作表自动列宽和首行加粗 * param ws */ private static void setColumnAutoSize(WritableSheet ws,int extraWith) /获取本列的最宽单元格的宽度 for(int i=0;iws.getColumns();i+) int colWith=0; for(int j=0;jws.getRows();j+) String content=ws.getCell(i,j).getContents().toString(); int cellWith=content.length
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 公司新产品下线节目策划方案
- 公司效能提升年活动方案
- 公司气球派对活动方案
- 公司新年开工活动方案
- 公司生日福利活动方案
- 公司组织避暑活动方案
- 公司搬新办公室活动方案
- 公司节目展示策划方案
- 公司活动烧烤策划方案
- 公司盈利模式策划方案
- 诊所院内感染管理制度
- 2025-2030年中国经颅磁刺激仪行业市场现状供需分析及投资评估规划分析研究报告
- 2025年江苏高考历史真题(解析版)
- 广西来宾市2023-2024学年高二下学期7月期末考试物理试题(含答案)
- 会员月底抽奖活动方案
- 2025年互联网医疗平安好医生阿里健康京东健康对比分析报告
- 攀枝花市仁和区社会招考社区工作者考试真题2024
- 2025年上海杨浦区七下英语期末达标检测试题含答案
- 老年外科患者围手术期营养支持中国专家共识(2024)解读
- 临床肘关节损伤影像诊断
- 2025家庭装饰装修合同范本
评论
0/150
提交评论