




版權(quán)說(shuō)明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
1、JAVA POI數(shù)據(jù)導(dǎo)入導(dǎo)出工具類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-ge
2、nerated 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 : 導(dǎo)入導(dǎo)出Excel工具類 * Version : 1.0.0 */ public class ExcelUtil /* * MethodName
3、 : 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é)院名稱,則可以這樣寫(xiě) * fieldMap.put("college.collegeName","學(xué)院名稱") * param she
4、etName 工作表的名稱 * 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
5、) throw new ExcelException("數(shù)據(jù)源中沒(méi)有任何數(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è)的過(guò)程 /1.計(jì)算一共有多少個(gè)工作表 double sh
6、eetNum=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.createSh
7、eet(sheetName+(i+1), i); /獲取開(kā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(); /如果是ExcelExceptio
8、n,則直接拋出 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)系
9、* 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 * Descr
10、iption : 導(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, S
11、tring 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"); /改成
12、輸出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(); /如果是ExcelExcepti
13、on,則直接拋出 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 respo
14、nse 使用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); /* * MethodNa
15、me : 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
16、static <T> List<T> excelToList( InputStream in, String sheetName, Class<T> entityClass, LinkedHashMap<String, String> fieldMap, String uniqueFields ) throws ExcelException /定義要返回的list List<T> resultList=new ArrayList<T>(); try /根據(jù)Excel數(shù)據(jù)源創(chuàng)建WorkBook Workbook wb=Wor
17、kbook.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
18、() nullCols+; if(nullCols=sheet.getColumns() break; else realRows+; /如果Excel中沒(méi)有數(shù)據(jù)則提示錯(cuò)誤 if(realRows<=1) throw new ExcelException("Excel文件中沒(méi)有任何數(shù)據(jù)"); Cell firstRow=sheet.getRow(0); String excelFieldNames=new StringfirstRow.length; /獲取Excel中的列名 for(int i=0;i<firstRow.length;i+) excelFiel
19、dNamesi=firstRowi.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
20、ExcelException("Excel中缺少必要的字段,或字段名稱有誤"); /將列名和列號(hào)放入Map中,這樣通過(guò)列名就可以拿到列號(hào) LinkedHashMap<String, Integer> colMap=new LinkedHashMap<String, Integer>(); for(int i=0;i<excelFieldNames.length;i+) colMap.put(excelFieldNamesi, firstRowi.getColumn(); /判斷是否有重復(fù)行 /1.獲取uniqueFields指定的列 Cell
21、uniqueCells=new CelluniqueFields.length; for(int i=0;i<uniqueFields.length;i+) int col=colMap.get(uniqueFieldsi); uniqueCellsi=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=uniqueCellsji.getContents
22、(); 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中有重復(fù)行,請(qǐng)檢查"); /將sheet轉(zhuǎn)換為list
23、 for(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)容
24、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
25、再拋出 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, Obje
26、ct 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 *
27、 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) re
28、turn field; /否則,查看父類中是否存在此字段,如果有則返回 Class<?> superClazz=clazz.getSuperclass(); if(superClazz!=null && superClazz !=Object.class) return getFieldByName(fieldName, superClazz); /如果本類和父類都沒(méi)有,則返回空 return null; /* * MethodName : getFieldValueByNameSequence * Description : * 根據(jù)帶路徑或不帶路徑的屬性名獲取屬
29、性值 * 即接受簡(jiǎn)單屬性名,如userName等,又接受帶路徑的屬性名,如等 * * 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)行拆分 St
30、ring attributes=fieldNameSequence.split("."); if(attributes.length=1) value=getFieldValueByName(fieldNameSequence, o); else /根據(jù)屬性名獲取屬性對(duì)象 Object fieldObj=getFieldValueByName(attributes0, o); String subFieldNameSequence=fieldNameSequence.substring(fieldNameSequence.indexOf(".")+1);
31、 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) thro
32、ws 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 = fi
33、eldType) 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
34、 = 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().
35、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() +
36、"類不存在字段名 "+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
溫馨提示
- 1. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 2024年家具制造機(jī)械項(xiàng)目資金需求報(bào)告代可行性研究報(bào)告
- 2022年大學(xué)英語(yǔ)考試模擬卷270測(cè)
- 2022年大連交通大學(xué)自考英語(yǔ)(二)練習(xí)題(附答案解析)
- 幼兒園小班數(shù)學(xué)三只熊的早餐教案
- 2024北京九中高二(下)開(kāi)學(xué)考語(yǔ)文試題及答案
- 2025年國(guó)際市場(chǎng)分析與策略能力測(cè)評(píng)試卷及答案
- 《連鎖經(jīng)營(yíng)》課件項(xiàng)目八連鎖
- 2025年公共衛(wèi)生管理專業(yè)研究生入學(xué)考試試卷及答案
- 中職班團(tuán)活動(dòng)策劃與實(shí)施
- 2025年信息安全工程師職業(yè)資格考試試卷及答案
- 國(guó)家開(kāi)放大學(xué)《土地利用規(guī)劃》本章自測(cè)參考答案
- 外賣安全法律知識(shí)講座
- 重癥醫(yī)學(xué)科的建設(shè)與管理指南(2023版)
- 資產(chǎn)評(píng)估(專升本)
- 社會(huì)工作服務(wù)項(xiàng)目指標(biāo)完成進(jìn)度表(模板)
- 二代征信系統(tǒng) 個(gè)人信用報(bào)告解讀
- 讀書(shū)分享交流會(huì)《從一到無(wú)窮大》課件
- 漢字的發(fā)展(英文版介紹)Chinese-character
- 土地利用現(xiàn)狀分類代碼表
- (完整版)生產(chǎn)車間地面畫(huà)線標(biāo)準(zhǔn)
- 單位財(cái)務(wù)內(nèi)控制度
評(píng)論
0/150
提交評(píng)論