JAVA POI通用工具类
更新时间:2024-04-13 12:41:01 阅读量: 综合文库 文档下载
- java培训班推荐度:
- 相关推荐
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(\学院名称\ * @param sheetName 工作表的名称
* @param sheetSize 每个工作表中记录的最大个数 * @param out 导出流 * @throws ExcelException */
public static
LinkedHashMap
OutputStream out
) throws ExcelException{
if(list.size()==0 || list==null){
throw new ExcelException(\数据源中没有任何数据\ }
if(sheetSize>65535 || sheetSize<1){ 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; i //如果只有一个工作表的情况 if(1==sheetNum){ WritableSheet sheet=wwb.createSheet(sheetName, i); fillSheet(sheet, list, fieldMap, 0, list.size()-1); //有多个工作表的情况 }else{ WritableSheet sheet=wwb.createSheet(sheetName+(i+1), i); //获取开始索引和结束索引 int firstIndex=i*sheetSize; int lastIndex=(i+1)*sheetSize-1>list.size()-1 (i+1)*sheetSize-1; ? list.size()-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 LinkedHashMap 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 LinkedHashMap HttpServletResponse response ) throws ExcelException{ //设置默认文件名为当前时间:年月日时分秒 String fileName=new SimpleDateFormat(\Date()).toString(); //设置response头信息 response.reset(); response.setContentType(\ //改成输出excel文件 response.setHeader(\filename=\ //创建工作簿并发送到浏览器 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 LinkedHashMap 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 LinkedHashMap //定义要返回的list List try { //根据Excel数据源创建WorkBook Workbook wb=Workbook.getWorkbook(in); //获取工作表 Sheet sheet=wb.getSheet(sheetName); //获取工作表的有效行数 int realRows=0; for(int i=0;i int nullCols=0; for(int j=0;j nullCols++; } } if(nullCols==sheet.getColumns()){ break; }else{ realRows++; } } //如果Excel中没有数据则提示错误 if(realRows<=1){ throw new ExcelException(\文件中没有任何数据\ } || Cell[] firstRow=sheet.getRow(0); String[] excelFieldNames=new String[firstRow.length]; //获取Excel中的列名 for(int i=0;i excelFieldNames[i]=firstRow[i].getContents().toString().trim(); \ Integer>(); } //判断需要的字段在Excel中是否都存在 boolean isExist=true; List throw new ExcelException(\中缺少必要的字段,或字段名称有误} //将列名和列号放入Map中,这样通过列名就可以拿到列号 LinkedHashMap colMap.put(excelFieldNames[i], firstRow[i].getColumn()); } //判断是否有重复行 //1.获取uniqueFields指定的列 Cell[][] uniqueCells=new Cell[uniqueFields.length][]; for(int i=0;i //2.从指定列中寻找重复行 for(int i=1;i for(int j=0;j String currentContent=uniqueCells[j][i].getContents(); Cell sameCell=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){ nullCols++; } } if(nullCols==uniqueFields.length){ throw new ExcelException(\中有重复行,请检查\ } } //将sheet转换为list for(int i=1;i //新建要转换的对象 T entity=entityClass.newInstance(); //给对象中的字段赋值 for(Entry 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() + \类不存在字段名 \ } 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等,又接受带路径的属性名,如student.department.name等 * * @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(attributes[0], o); String subFieldNameSequence=fieldNameSequence.substring(fieldNameSequence.indexOf(\ 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(\HH:mm:ss\ }else{ field.set(o, fieldValue); } }else{ throw new ExcelException(o.getClass().getSimpleName() + \类不存在字段名 \ } } /** * @MethodName : setColumnAutoSize * @Description : 设置工作表自动列宽和首行加粗 * @param ws */ private static void setColumnAutoSize(WritableSheet ws,int extraWith){ //获取本列的最宽单元格的宽度 for(int i=0;i for(int j=0;j String content=ws.getCell(i,j).getContents().toString(); int cellWith=content.length(); if(colWith //设置单元格的宽度为最宽宽度+额外宽度 ws.setColumnView(i, colWith+extraWith); } } /** * @MethodName : fillSheet * @Description : 向工作表中填充数据 * @param sheet 工作表 * @param list 数据源 * @param fieldMap 中英文字段对应关系的Map * @param firstIndex 开始索引 * @param lastIndex 结束索引 */ private static LinkedHashMap )throws Exception{ //定义存放英文字段名和中文字段名的数组 String[] enFields=new String[fieldMap.size()]; String[] cnFields=new String[fieldMap.size()]; //填充数组 int count=0; for(Entry //填充表头 for(int i=0;i Label label=new Label(i,0,cnFields[i]); sheet.addCell(label); } //填充内容 int rowNo=1; for(int index=firstIndex;index<=lastIndex;index++){ //获取单个对象 T item=list.get(index); for(int i=0;i Object objValue=getFieldValueByNameSequence(enFields[i], item); String fieldValue=objValue==null ? \ Label label =new Label(i,rowNo,fieldValue); sheet.addCell(label); } rowNo++; } //设置自动列宽 setColumnAutoSize(sheet, 5); } }
正在阅读:
JAVA POI通用工具类04-13
发挥园区载体作用推动产业集群发展10-20
《杯弓蛇影》教学设计03-17
浅谈小学语文课堂教学改革08-15
美丽的果园作文450字06-27
路桥施工重大事故应急救援处理预案06-29
安乡一中2017届高考语文考前冲刺练习(1---10) 学生(附答案) 龚05-09
壶口瀑布说课04-23
浅谈现阶段监理工程师的投资控制07-19
- 2009中西部家居博览会总体策划
- 2009 Revit 1级工程师学生用
- 天津地铁建设工程试验检测机构管理办法(TJDT-ZY-AQ-29)
- 新四年级数学暑期班第七次教案
- 机械制造企业隐患排查治理检查表 - 图文
- 2008届全国百套高考数学模拟试题分类汇编-103概率与统计解答题 -
- 职场健身防病试题及答案
- Excel操作技巧大全II - --数据输入和编辑技巧
- 南开大学2018春季《行政管理学》离线作业考核答案
- 2015年医师定考简易程序试卷及答案
- 新《预算法》对行政事业单位预算管理的挑战解读
- 轴的课件
- 电动汽车充电桩设计 毕业论文
- 必修2、选修2-1、1-1期末模拟试题2
- 桌面远程运维管理系统实施-可行性研究报告120306
- 西气东输水土保持工程工作总结 - 图文
- 正宁县基本县情及经济社会发展情况简介
- SATWE参数设置(巨详细)
- 儒家法思想研究综述
- 生活家政服务电子商务平台建设运营整合方案书【审报完稿】
- 通用
- 工具
- JAVA
- POI
- 2018年高考数学分类汇编复数、向量等7个板块试题及答案详解
- 地貌期末复习1
- 厨师考核管理办法
- 某省财政项目跟踪审计投标方案
- 领导干部不违规收送红包礼金承诺书
- 幼儿园集团化办园工作实施方案 1doc
- 售后工资绩效考核方案
- 实验 图形用户界面1
- LTE物理层总结二-1
- 会计继续教育测试题及参考答案2018
- 道路运输企业安全标准化达标考核考评员试题及答案
- 2013年广东实验中学顺德学校青年礼活动方案
- 2011高考数学知识点一本全
- 华南理工高级语言程序设计C++随堂练习答案
- 汽车知识竞赛题库
- 最新北师大版2018-2019学年数学七年级上册《展开与折叠》同步练
- 2016威海一摸语文试题含答案(逐题详解)
- AT89C51 52 55单片机编程器(烧写器)制作 - 图文
- 人教版小学四年级数学上册期中测试卷
- 行政法笔记