前段時(shí)間做的分布式集成平臺(tái)項(xiàng)目中,許多模塊都用到了導(dǎo)入導(dǎo)出Excel的功能,于是決定封裝一個(gè)ExcelUtil類,專門用來處理Excel的導(dǎo)入和導(dǎo)出
?
本項(xiàng)目的持久化層用的是JPA(底層用hibernate實(shí)現(xiàn)),所以導(dǎo)入和導(dǎo)出也都是基于實(shí)體類的。
?
在編寫ExcelUtil之前,在網(wǎng)上查了一些資料。java中用來處理Excel的第三方開源項(xiàng)目主要就是POI和JXL。poi功能強(qiáng)大,但是比較耗資源,對(duì)于大數(shù)據(jù)量的導(dǎo)入導(dǎo)出性能不是太好;jxl功能簡(jiǎn)單,但是性能比較好。
?
由于本項(xiàng)目的導(dǎo)入導(dǎo)出更多關(guān)注性能問題,而且jxl提供的功能基本也都?jí)蛴昧?#xff0c;于是選擇了jxl作為支持。
?
實(shí)戰(zhàn)
?
導(dǎo)出就是將List轉(zhuǎn)化為Excel(listToExcel)
導(dǎo)入就是將Excel轉(zhuǎn)化為L(zhǎng)ist(excelToList)
?
導(dǎo)入導(dǎo)出中會(huì)出現(xiàn)各種各樣的問題,比如:數(shù)據(jù)源為空、有重復(fù)行等,我自定義了一個(gè)ExcelException異常類,用來處理這些問題。
?
ExcelException類
package common.tool.excel;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}}
下面就是該文的主角ExcelUtil登場(chǎng)了,作為一個(gè)工具類,其內(nèi)的所有方法都是靜態(tài)的,方便使用。?
ExcelUitl類
/*** @author : WH* @group : tgb8* @Date : 2014-1-2 下午9:13:21* @Comments : 導(dǎo)入導(dǎo)出Excel工具類* @Version : 1.0.0*/public class ExcelUtil {/*** @MethodName : listToExcel* @Description : 導(dǎo)出Excel(可以導(dǎo)出到本地文件系統(tǒng),也可以導(dǎo)出到瀏覽器,可自定義工作表大小)* @param list 數(shù)據(jù)源* @param fieldMap 類的英文屬性和Excel中的中文列名的對(duì)應(yīng)關(guān)系* 如果需要的是引用對(duì)象的屬性,則英文屬性使用類似于EL表達(dá)式的格式* 如:list中存放的都是student,student中又有college屬性,而我們需要學(xué)院名稱,則可以這樣寫* fieldMap.put("college.collegeName","學(xué)院名稱")* @param sheetName 工作表的名稱* @param sheetSize 每個(gè)工作表中記錄的最大個(gè)數(shù)* @param out 導(dǎo)出流* @throws ExcelException*/public static <T> void listToExcel (List<T> list ,LinkedHashMap<String,String> fieldMap,String sheetName,int sheetSize,OutputStream out) throws ExcelException{if(list.size()==0 || list==null){throw new ExcelException("數(shù)據(jù)源中沒有任何數(shù)據(jù)");}if(sheetSize>65535 || sheetSize<1){sheetSize=65535;}//創(chuàng)建工作簿并發(fā)送到OutputStream指定的地方WritableWorkbook wwb;try {wwb = Workbook.createWorkbook(out);//因?yàn)?003的Excel一個(gè)工作表最多可以有65536條記錄,除去列頭剩下65535條//所以如果記錄太多,需要放到多個(gè)工作表中,其實(shí)就是個(gè)分頁(yè)的過程//1.計(jì)算一共有多少個(gè)工作表double sheetNum=Math.ceil(list.size()/new Integer(sheetSize).doubleValue());//2.創(chuàng)建相應(yīng)的工作表,并向其中填充數(shù)據(jù)for(int i=0; i<sheetNum; i++){//如果只有一個(gè)工作表的情況if(1==sheetNum){WritableSheet sheet=wwb.createSheet(sheetName, i);fillSheet(sheet, list, fieldMap, 0, list.size()-1);//有多個(gè)工作表的情況}else{WritableSheet sheet=wwb.createSheet(sheetName+(i+1), i);//獲取開始索引和結(jié)束索引int firstIndex=i*sheetSize;int lastIndex=(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 (Exception e) {e.printStackTrace();//如果是ExcelException,則直接拋出if(e instanceof ExcelException){throw (ExcelException)e;//否則將其它異常包裝成ExcelException再拋出}else{throw new ExcelException("導(dǎo)出Excel失敗");}}}/*** @MethodName : listToExcel* @Description : 導(dǎo)出Excel(可以導(dǎo)出到本地文件系統(tǒng),也可以導(dǎo)出到瀏覽器,工作表大小為2003支持的最大值)* @param list 數(shù)據(jù)源* @param fieldMap 類的英文屬性和Excel中的中文列名的對(duì)應(yīng)關(guān)系* @param out 導(dǎo)出流* @throws ExcelException*/public static <T> void listToExcel (List<T> list ,LinkedHashMap<String,String> fieldMap,String sheetName,OutputStream out) throws ExcelException{listToExcel(list, fieldMap, sheetName, 65535, out);}/*** @MethodName : listToExcel* @Description : 導(dǎo)出Excel(導(dǎo)出到瀏覽器,可以自定義工作表的大小)* @param list 數(shù)據(jù)源* @param fieldMap 類的英文屬性和Excel中的中文列名的對(duì)應(yīng)關(guān)系* @param sheetSize 每個(gè)工作表中記錄的最大個(gè)數(shù)* @param response 使用response可以導(dǎo)出到瀏覽器* @throws ExcelException*/public static <T> void listToExcel (List<T> list ,LinkedHashMap<String,String> fieldMap,String sheetName,int sheetSize,HttpServletResponse response ) throws ExcelException{//設(shè)置默認(rèn)文件名為當(dāng)前時(shí)間:年月日時(shí)分秒String fileName=new SimpleDateFormat("yyyyMMddhhmmss").format(new Date()).toString();//設(shè)置response頭信息response.reset(); response.setContentType("application/vnd.ms-excel"); //改成輸出excel文件response.setHeader("Content-disposition","attachment; filename="+fileName+".xls" );//創(chuàng)建工作簿并發(fā)送到瀏覽器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("導(dǎo)出Excel失敗");}}}/*** @MethodName : listToExcel* @Description : 導(dǎo)出Excel(導(dǎo)出到瀏覽器,工作表的大小是2003支持的最大值)* @param list 數(shù)據(jù)源* @param fieldMap 類的英文屬性和Excel中的中文列名的對(duì)應(yīng)關(guān)系* @param response 使用response可以導(dǎo)出到瀏覽器* @throws ExcelException*/public static <T> void listToExcel (List<T> list ,LinkedHashMap<String,String> fieldMap,String sheetName,HttpServletResponse response ) throws ExcelException{listToExcel(list, fieldMap, sheetName, 65535, response);}/*** @MethodName : excelToList* @Description : 將Excel轉(zhuǎn)化為L(zhǎng)ist* @param in :承載著Excel的輸入流* @param sheetIndex :要導(dǎo)入的工作表序號(hào)* @param entityClass :List中對(duì)象的類型(Excel中的每一行都要轉(zhuǎn)化為該類型的對(duì)象)* @param fieldMap :Excel中的中文列頭和類的英文屬性的對(duì)應(yīng)關(guān)系Map* @param uniqueFields :指定業(yè)務(wù)主鍵組合(即復(fù)合主鍵),這些列的組合不能重復(fù)* @return :List* @throws ExcelException*/public static <T> List<T> excelToList(InputStream in,String sheetName,Class<T> entityClass,LinkedHashMap<String, String> fieldMap,String[] uniqueFields) throws ExcelException{//定義要返回的listList<T> resultList=new ArrayList<T>();try {//根據(jù)Excel數(shù)據(jù)源創(chuàng)建WorkBookWorkbook wb=Workbook.getWorkbook(in);//獲取工作表Sheet sheet=wb.getSheet(sheetName);//獲取工作表的有效行數(shù)int realRows=0;for(int i=0;i<sheet.getRows();i++){int nullCols=0;for(int j=0;j<sheet.getColumns();j++){Cell currentCell=sheet.getCell(j,i);if(currentCell==null || "".equals(currentCell.getContents().toString())){nullCols++;}}if(nullCols==sheet.getColumns()){break;}else{realRows++;}}//如果Excel中沒有數(shù)據(jù)則提示錯(cuò)誤if(realRows<=1){throw new ExcelException("Excel文件中沒有任何數(shù)據(jù)");}Cell[] firstRow=sheet.getRow(0);String[] excelFieldNames=new String[firstRow.length];//獲取Excel中的列名for(int i=0;i<firstRow.length;i++){excelFieldNames[i]=firstRow[i].getContents().toString().trim();}//判斷需要的字段在Excel中是否都存在boolean isExist=true;List<String> excelFieldList=Arrays.asList(excelFieldNames);for(String cnName : fieldMap.keySet()){if(!excelFieldList.contains(cnName)){isExist=false;break;}}//如果有列名不存在,則拋出異常,提示錯(cuò)誤if(!isExist){throw new ExcelException("Excel中缺少必要的字段,或字段名稱有誤");}//將列名和列號(hào)放入Map中,這樣通過列名就可以拿到列號(hào)LinkedHashMap<String, Integer> colMap=new LinkedHashMap<String, Integer>();for(int i=0;i<excelFieldNames.length;i++){colMap.put(excelFieldNames[i], firstRow[i].getColumn());} //判斷是否有重復(fù)行//1.獲取uniqueFields指定的列Cell[][] uniqueCells=new Cell[uniqueFields.length][];for(int i=0;i<uniqueFields.length;i++){int col=colMap.get(uniqueFields[i]);uniqueCells[i]=sheet.getColumn(col);}//2.從指定列中尋找重復(fù)行for(int i=1;i<realRows;i++){int nullCols=0;for(int j=0;j<uniqueFields.length;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("Excel中有重復(fù)行,請(qǐng)檢查");}}//將sheet轉(zhuǎn)換為listfor(int i=1;i<realRows;i++){//新建要轉(zhuǎn)換的對(duì)象T entity=entityClass.newInstance();//給對(duì)象中的字段賦值for(Entry<String, String> entry : fieldMap.entrySet()){//獲取中文字段名String cnNormalName=entry.getKey();//獲取英文字段名String enNormalName=entry.getValue();//根據(jù)中文字段名獲取列號(hào)int col=colMap.get(cnNormalName);//獲取當(dāng)前單元格中的內(nèi)容String content=sheet.getCell(col, i).getContents().toString().trim();//給對(duì)象賦值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("導(dǎo)入Excel失敗");}}return resultList;}/*<-------------------------輔助的私有方法----------------------------------------------->*//*** @MethodName : getFieldValueByName* @Description : 根據(jù)字段名獲取字段值* @param fieldName 字段名* @param o 對(duì)象* @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 : 根據(jù)字段名獲取字段* @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 : * 根據(jù)帶路徑或不帶路徑的屬性名獲取屬性值* 即接受簡(jiǎn)單屬性名,如userName等,又接受帶路徑的屬性名,如student.department.name等* * @param fieldNameSequence 帶路徑的屬性名或簡(jiǎn)單屬性名* @param o 對(duì)象* @return 屬性值* @throws Exception*/private static Object getFieldValueByNameSequence(String fieldNameSequence, Object o) throws Exception{Object value=null;//將fieldNameSequence進(jìn)行拆分String[] attributes=fieldNameSequence.split("\\.");if(attributes.length==1){value=getFieldValueByName(fieldNameSequence, o);}else{//根據(jù)屬性名獲取屬性對(duì)象Object fieldObj=getFieldValueByName(attributes[0], o);String subFieldNameSequence=fieldNameSequence.substring(fieldNameSequence.indexOf(".")+1);value=getFieldValueByNameSequence(subFieldNameSequence, fieldObj);}return value; } /*** @MethodName : setFieldValueByName* @Description : 根據(jù)字段名給對(duì)象的字段賦值* @param fieldName 字段名* @param fieldValue 字段值* @param o 對(duì)象*/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(); //根據(jù)字段類型給字段賦值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 : 設(shè)置工作表自動(dòng)列寬和首行加粗* @param ws*/private static void setColumnAutoSize(WritableSheet ws,int extraWith){//獲取本列的最寬單元格的寬度for(int i=0;i<ws.getColumns();i++){int colWith=0;for(int j=0;j<ws.getRows();j++){String content=ws.getCell(i,j).getContents().toString();int cellWith=content.length();if(colWith<cellWith){colWith=cellWith;}}//設(shè)置單元格的寬度為最寬寬度+額外寬度ws.setColumnView(i, colWith+extraWith);}}/*** @MethodName : fillSheet* @Description : 向工作表中填充數(shù)據(jù)* @param sheet 工作表 * @param list 數(shù)據(jù)源* @param fieldMap 中英文字段對(duì)應(yīng)關(guān)系的Map* @param firstIndex 開始索引* @param lastIndex 結(jié)束索引*/private static <T> void fillSheet(WritableSheet sheet,List<T> list,LinkedHashMap<String,String> fieldMap,int firstIndex,int lastIndex)throws Exception{//定義存放英文字段名和中文字段名的數(shù)組String[] enFields=new String[fieldMap.size()];String[] cnFields=new String[fieldMap.size()];//填充數(shù)組int count=0;for(Entry<String,String> entry:fieldMap.entrySet()){enFields[count]=entry.getKey();cnFields[count]=entry.getValue();count++;}//填充表頭for(int i=0;i<cnFields.length;i++){Label label=new Label(i,0,cnFields[i]);sheet.addCell(label);}//填充內(nèi)容int rowNo=1;for(int index=firstIndex;index<=lastIndex;index++){//獲取單個(gè)對(duì)象T item=list.get(index);for(int i=0;i<enFields.length;i++){Object objValue=getFieldValueByNameSequence(enFields[i], item);String fieldValue=objValue==null ? "" : objValue.toString();Label label =new Label(i,rowNo,fieldValue);sheet.addCell(label);}rowNo++;}//設(shè)置自動(dòng)列寬setColumnAutoSize(sheet, 5);}}
該工具類有4個(gè)重載的導(dǎo)出方法和1個(gè)導(dǎo)入方法,大家可以根據(jù)實(shí)際情況進(jìn)行選擇。
?
總結(jié)
導(dǎo)入和導(dǎo)出方法都是通過傳一個(gè)fieldMap參數(shù)(類的英文屬性和Excel的中文列頭的對(duì)應(yīng)關(guān)系)來連接實(shí)體類和Excel的
導(dǎo)出的時(shí)候可以選擇導(dǎo)出到本地文件系統(tǒng)或?qū)С龅綖g覽器,也可以自定義每個(gè)工作表的大小
導(dǎo)入的時(shí)候可以自定義業(yè)務(wù)主鍵組合uniqueFields,這樣就可以檢測(cè)Excel中是否有重復(fù)行了
總結(jié)
以上是生活随笔為你收集整理的Java导入导出Excel工具类ExcelUtil的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。