文件導入導出必須代碼
exportexcel.java
/***版權所有©2012-2014 <a href =“ https://github.com/thinkgem/jeesite”> jeesite </a>保留所有權利。 */package com.thinkgem.jeesite.common.utils.excel;導入import import java.io.io.fileNotFoundException; import java.io.fileOutputputstream; import java.io.io.io.io.io.io.io.io.io.io.io.io java java.io.outputstream; import java.lang.reflect.field.field; import java java.util.comparator; import java.util.date; import java.util.hashmap; import java.util.linkedhashmap; import java.util.list; import java java.util.map;導入javax.servlet.http.httpservletresponse; import org.apache.commons.lang3.StringUtils;import org.apache.poi.ss.usermodel.Cell;import org.apache.poi.ss.usermodel.CellStyle;import org.apache.poi.ss.usermodel.Comment;import org.apache.poi.ss.usermodel.DataFormat;import org.apache.poi.ss.usermodel.font; import org.apache.poi.ss.usermodel.indexedColors; import org.apache.poi.poi.ss.s.s.usermodel.row; import org.apache.apache.poi.poi.ss.usermodel.s.usermodel.sheet.sheet org.apache.poi.ss.util.cellrangeaddress; import org.apache.poi.xssf.streaming.sxssfworkbook; import org.apace.poi.xssf.usermodel.xssssssssssfclient.import org org org.apache.pocace.poii.xsssssssssssssssssf.usermodelrich.usermodelricher.usermodelrich.usermodellicher.usemermodelchricherclich; org.slf4j.logger;導入org.slf4j.loggerfactory;導入com.google.common.collect.lists; import com.thinkgem.jeesite.common.utils.dateutils;導入com.thinkgem.jeesite.common.utils.encodes; import com.thinkgem.thinkgem.jeesite.common.common.utils.utils.reflections; inocut; incupt; impots; incuts; incort; impots; impots; com.thinkgem.jeesite.common.utils.excel.annotation.excelfield; import com.thinkgem.jeesite.modules.sys.utils.dictutils; /** *導出excel 文件(導出“ xlsx”, @ @@see org.apache.poi.ss.s.sspreadsheetversion) * @author thinkgem * @version 2013-04-21 */public class class class class exportexcel {private static logger loggerfactory.getlogger.getLogger(exportexper.class); / ** *工作薄對象 */私人sxssfworkbook wb; / ** *工作表對象 */私人工作表; / ** *樣式列表 */私有地圖<字符串,CellStyle>樣式; / ** *當前行號 */ private int rownum; /** * 註解列表( object [] {Excelfield,field/method}) */list <object []> annotationList = lists.newarraylist(); / ** *字段映射 */ linkedhashmap <字符串,字符串> fieldmap; hashmap <string,string> candtypes; / ** *構造函數 * @param title表格標題,傳“空值”,表示無標題 * @param cls實體對象,通過antotation.exportfield獲取標題 */ public exportexcel(string title,class <? > cls){this(title(title,cls,cls,1); } / ** *構造函數 * @param title表格標題,傳“空值”,表示無標題 * @param fieldmap,獲取要導出的字段和字段標題 * / public exportexcel(字符串標題,linkedhashmap <string,string> fieldmap){this.fieldmap = fieldmap; fieldmap; disttypes = new Hashmap <string,string>(); //初始化int colunm = 0; List <String> headerList = lists.newarraylist(); for(字符串鍵:fieldmap.keyset()){字符串t = fieldmap.get(key); hashmap <string,string> map = com.thinkgem.jeesite.common.utils.stringutils.tomap(t,';“;”,“ =”,false); if(map.get(“ name”)!= null){t = map.get(“ name”); } if(map.get(“ disttype”)!= null){disttypes.put(“”+(colunm),map.get(“ disttype”)); } colunm ++; headerList.Add(t); } initialize(title,headerList); } / ** *構造函數 * @param標題表格標題,“空值”,表示無標題 * @param cls cls實體對象,通過Cls.GetDeclaredFields(); for(field f:fs){expelfield ef = f.getAnnotation(excelfield.class); if(ef!= null &&(ef.type()== 0 || ef.type()== type)){if(groups!= null && groups.length> 0){boolean ingroup = false; for(int g:groups){if(indroup){break; } for(int efg:ef.groups()){if(g == efg){indroup = true; AnnotationList.Add(new Object [] {EF,F});休息; }}}} else {annotationList.add(new Object [] {Ef,f}); }}} //獲取註釋方法[] ms = cls.getDeclaredMethods(); for(方法m:ms){excelfield ef = m.getantation(excelfield.class); if(ef! = null &&(ef.type()== 0 || ef.type()== type)){if(groups!= null && groups.length> 0){boolean ingroup = false; for(int g:groups){if(indroup){break; } for(int efg:ef.groups()){if(g == efg){indroup = true; AnnotationList.Add(new Object [] {EF,M});休息; }}}} else {annotationList.add(new Object [] {Ef,m}); }}} //字段排序collections.sort(AnnoTationList,new Comparator <對象[]>(){public int comparare(object [] o1,object [] o2){return new new Integer(((ExceLfield)o1 [0])。 //初始化列表<String> headerList = lists.newarraylist(); for(object [] OS:AnnotationList){字符串t =((ExceLfield)OS [0])。title(); //如果是導出,則去掉註釋if(ss.length == 2){t = ss [0]; }} headerlist.add(t); } initialize(title,headerList); } / ** *構造函數 * @param title表格標題,傳“空值”,表示無標題 * @param headers表頭數組 * / public exportexcel(字符串title,string [] headers){initialize(stition,lists.newarraylist(newarraylist(headers))); } / ** *構造函數 * @param標題表格標題,傳“空值”,表示無標題 * @param headerList表頭列表 * / public exportexcel(字符串標題,list <string> string> string> headerList){initialize(initialize,title,headerList); } / ** *初始化函數 * @param title表格標題,傳“空值”,表示無標題 * @param headerList表頭列表 * / private void initialize(字符串標題,列表<string> headerList){this.wb = new sxsssfworkbook(500); this.sheet = wb.createsheet(“ export”); this.Styles = Createstyles(WB); //創建標題if(stringutils.isnotblank(title)){row titlerow = Sheet.Createrow(Rownum ++); Titlerow.setheighinpoints(30); Cell TitleCell = Titlerow.CreateCell(0); titlecell.setCellstyle(styles.get(“ title”)); titlecell.setCellvalue(title); Sheet.AddmergedRegion(new CellRangeadDress(titlerow.getRownum(),titlerow.getRownum(),titlerow.getRownum(),headerlist.size() - 1)); } //創建標頭如果(headerList == null){拋出新的RunTimeException(“ headerList not null! ”); }行Headerrow = Sheet.Createrow(Rownum ++); headerrow.setheighinpoints(16); for(int i = 0; i <headerlist.size(); i ++){cell = headerrow.createcell(i); Cell.SetCellstyle(styles.get(“ header”)); string [] ss = stringutils.split(headerlist.get(i),“ **”,2); if(ss.length == 2){cell.setCellvalue(ss [0]);評論評論= this.sheet.createdrawingpatriarch()。createCellComment(new xssfclientanchor(0,0,0,0,0,0,(short)3,3,3,(short)5,6); comment.setString(新的XSSFRICHTEXTSTRING(SS [1])); Cell.SetCellComment(註釋); } else {cell.setCellvalue(headerList.get(i)); } sheet.autosizecolumn(i); } for(int i = 0; i <headerlist.size(); i ++){int colwidth = Sheet.getColumnWidth(i)*2; Sheet.SetColumnWidth(I,Colwidth <3000?3000:Colwidth); } log.debug(“初始化成功。”); } / ** *創建表格樣式 * @param wb工作薄對象 * @return樣式列表 * / private Map <string,cellstyle> createStyles(Workbook wb){Map <string,cellstyle> styles = new Hashmap <string,cellstyle>(); CellStyle樣式= WB.CreateCellstyle(); style.SetAlignment(CellStyle.Align_Center); style.setverticalAlignment(CellStyle.Vertical_Center);字體titlefont = wb.createfont(); titlefont.setFontName(“ arial”); titlefont.setfontheighinpoints(((簡)16); titlefont.setBoldWeight(font.boldweight_bold); style.setFont(titlefont); styles.put(“標題”,樣式); style = wb.createcellstyle(); style.setverticalAlignment(CellStyle.Vertical_Center); style.setBorderRight(cellstyle.border_thin); style.setRightBorderColor(indexedColors.grey_50_percent.getIndex()); style.setBorderLeft(cellstyle.border_thin); style.setleftborderColor(indexedColors.grey_50_percent.getIndex()); style.setBorderTop(cellstyle.border_thin); style.settopborderColor(indexedColors.grey_50_percent.getIndex()); style.setborderbottom(cellstyle.border_thin); style.setBottOmbOrtOrderColor(indexedColors.grey_50_percent.getIndex());字體datafont = wb.createfont(); datafont.setFontName(“ arial”); datafont.setfontheighinpoints((短)10); style.setFont(datafont); styles.put(“數據”,樣式); style = wb.createcellstyle(); style.clonestylefrom(styles.get(“ data”)); style.setAlignment(cellstyle.align_left); styles.put(“ data1”,樣式); style = wb.createcellstyle(); style.clonestylefrom(styles.get(“ data”)); style.SetAlignment(CellStyle.Align_Center); styles.put(“ data2”,樣式); style = wb.createcellstyle(); style.clonestylefrom(styles.get(“ data”)); style.setAlignment(cellstyle.align_right); styles.put(“ data3”,樣式); style = wb.createcellstyle(); style.clonestylefrom(styles.get(“ data”)); // style.setwraptext(true); style.SetAlignment(CellStyle.Align_Center); style.setFillForegroundColor(indexedColors.grey_50_percent.getIndex()); style.setFillPattern(cellstyle.solid_foreground);字體HeaderFont = wb.createfont(); headerFont.setFontName(“ arial”); headerfont.setfontheighinpoints((短)10); HeaderFont.SetBoldWeight(font.boldweight_bold); headerfont.setColor(indexedColors.white.getIndex()); style.setFont(HeaderFont); styles.put(“標題”,樣式);返回樣式; } / ** *添加一行 * @return行對象 * / public Row addrow(){return Sheet.Createrow(Rownum ++); } / ** *添加一個單元格 * @param row添加的行 * @param列 * @param val添加值 * @return單元格對象 * / public cell addCell(行行,int列,object val){return this.addcell(row,colund,column,val,val,0,class.class.class.class); } / ** *添加一個單元格 * @param行添加的行 * @param列 * @param val添加值 * @param val添加值 * @param align 對齊方式(1:靠左;2:靠左;2:居中;3:居中;) cellStyle style = styles.get(“ data”+(align> = 1 && align <= 3? align:“”));嘗試{if(val == null){cell.setCellvalue(“”); } else if(val instanceof string){cell.setCellvalue(((string)val); } else if(val instance of integer){cell.setCellvalue(((integer)val); } else if(val instance of long){cell.setCellvalue(((long)val); } else if(val instance of double){cell.setCellValue(新的Decimalformat(“。#####”)。格式(val)); } else if(val實例float){cell.setCellvalue(((float)val); } else if(val instanceof date){dataformat格式= wb.createDataFormat(); style.setDataFormat(format.getFormat(“ yyyy-mm-dd”)); cell.setCellvalue(dateUtils.formatdateTime(((date)val)); } else {if(fieldType!= class.class){cell.setCellValue(((string)fieldType.getMethod)(“ setValue”,object.class).invoke(null,val)); } else {cell.setCellValue(((string)class.forname(this.getClass()。getName()。 }}}} catch(exception ex){log.info(“ set cell value [“+row.getRownum()+”,“”+column+“] error:”+ex.toString()); Cell.SetCellValue(Val.toString()); } cell.setCellstyle(style);返回單元; } / ** * 添加數據(通過 annotation.exportfield添加數據) * @return list數據列表 * / public <e> exportexcel setDatalist(list <e> list){for(e e e:e:list){int colunm = 0;行行= this.addrow(); StringBuilder SB = new StringBuilder(); if(e instanceof map){@suppresswarnings(“ UNCANCED”)MAP <String,Object> Map =(Map <String,Object>)E; for(字符串鍵:fieldmap.keyset()){對象值= map.get(key);字符串columnDictType = disttypes.get(colunm+“”); if(strignutils.isnotblank(columnDictType)){value = dictutils.getDictLabel(value == null? “:value.tostring(),columndictType,”); } this.addcell(row,colunm ++,value == null?”“:value.tostring(),0,string.class); sb.Append(value +“,”); }} else {for(object [] OS:AnnotationList){Excelfield EF =(Excelfield)OS [0];對象val = null; //獲取實體值嘗試{if(strignutils.isnotblank(ef.value())){val = fellowions.invokegetter(e,ef.value()); } else {if(os [1]實例field){val = fellowions.invokegetter(e,(field)OS [1])。 getName()); } else if(os [1] instanceof方法){val = fellowions.invokemethod(e,((方法)OS [1])。getName(),new class [] {] {},new Object [] {] {] {}); }} //如果是dict,請獲取dict label,if(stringutils.isnotblank(ef.dicttype())){val = dictutils.getDictlabel(val == null?“:val.tostring(),ef.dicttype(ef.dicttype(), }} catch(異常EX){//未能忽略log.info(ex.toString()); val =“”; } this.addcell(row,colunm ++,val,ef.align(),ef.fieldtype()); sb.append(val +“,”); } log.debug(“寫成功:[“+row.getRownum()+”]”+sb.tostring()); }}返回此; } / ** *輸出數據流 * @param OS輸出數據流 * / public ExportExcel write(outputStream OS)拋出ioexception {wb.write(os);返回此; } / ** *輸出到客戶端 * @param fileName輸出文件名 * / public exportExcel write(httpservletresponse響應,字符串fileName)拋出ioexception {revestion.reset(); response.setContentType(“應用程序/八位字節; charset = utf-8”); wendment.setheader(“ content-disposition”,“ attactment; filename =“+encodes.urlencode(filename))); write(wendys.getOutputStream());返回此; } / ** *輸出到文件 * @param filename輸出文件名 * / public exportExcel writefile(string name)拋出fileNotFoundException,ioexception {fileOutputputstream os = new fileOttputStream(new fileotputstream); this.write(OS);返回此; } / ** *清理臨時文件 * / public ExportExcel dispose(){wb.dispose();返回此; }}}導出測試
public static void main(string [] args)拋出可投擲{list <string> headerList = lists.newarraylist(); for(int i = 1; i <= 10; i ++){headerlist.add(“表頭”+i); } list <string> datarOwlist = lists.newarraylist(); for(int i = 1; i <= headerList.size(); i ++){datarOwlist.add(“'數據”+i); } list <List <string >> datalist = lists.newarraylist(); for(int i = 1; i <= 1000000; i ++){datalist.add(dataRowlist); } exportExcel ee = new exportExcel(“表格標題”,headerList); for(int i = 0; i <datalist.size(); i ++){row row = ee.addrow(); for(int j = 0; j <datalist.get(i).size(); j ++){ee.addcell(row,j,datalist.get(i).get(j)); }} ee.writeFile(“ target/export.xlsx”); ee.dispose(); log.debug(“出口成功。”); }importexcel.java
/***版權所有©2012-2014 <a href =“ https://github.com/thinkgem/jeesite”> jeesite </a>保留所有權利。 */package com.thinkgem.jeesite.common.utils.excel; import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import java.lang.reflect.Field;import java.lang.reflect.Method;import java.util.Collections;import java.util.Comparator;import java.util.Date;import java.util.list;導入org.apache.commons.lang3.stringutils; import org.apache.poi.hssf.usermodel.hssfworkbook; import org.apache.openxml4j.exceptions.invalidformate; import org org.apache.poi.ss.usermodel.DateUtil;import org.apache.poi.ss.usermodel.Row;import org.apache.poi.ss.usermodel.Sheet;import org.apache.poi.ss.usermodel.Workbook;import org.apache.poi.xssf.usermodel.XSSFWorkbook;import org.slf4j.logger; import org.slf4j.loggerfactory; import org.springframework.web.multipart.multipart.multipartfile; import com.google.common.collect.Lists;import com.thinkgem.jeesite.common.utils.Reflections;import com.thinkgem.jeesite.common.utils.excel.annotation.ExcelField;import com.thinkgem.jeesite.modules.sys.utils.DictUtils; /** *導入excel 文件(支持“ xls”和“ xlsx”格式格式) / ** *工作薄對象 */私人工作簿WB; / ** *工作表對象 */私人工作表; / ** *標題行號 */私人int eNDERNUM; /** * 構造函數 * @param path 導入文件,讀取第一個工作表 * @param headerNum 標題行號,數據行號=標題行號+1 * @throws InvalidFormatException * @throws IOException */ public ImportExcel(String fileName, int headerNum) throws InvalidFormatException, IOException { this(new File(fileName), headerNum); } /** * 構造函數 * @param path 導入文件對象,讀取第一個工作表 * @param headerNum 標題行號,數據行號=標題行號+1 * @throws InvalidFormatException * @throws IOException */ public ImportExcel(File file, int headerNum) throws InvalidFormatException, IOException { this(file, headerNum, 0); } / ** *構造函數 * @param路徑 * * @param headerNum標題行號,數據行號=標題行號+1 * @param SheetIndex工作表編號SheetIndex); } /** * 構造函數 * @param path 導入文件對象 * @param headerNum 標題行號,數據行號=標題行號+1 * @param sheetIndex 工作表編號 * @throws InvalidFormatException * @throws IOException */ public ImportExcel(File file, int headerNum, int sheetIndex) throws InvalidFormatException, IOException { this(file.getName(), new fileInputStream(file),headernum,sheetIndex); } / ** *構造函數 * @param文件導入文件對象 * @param headernum標題行號,數據行號=標題行號+1 * @param sheetIndex工作表編號 * @throws invalidformateXpection * @throws ioexiption * / public importexcel(public importexcel)此(MultipArtFile.GetOriginalFileName(),MultipartFile.GetInputStream(),headerNum,SheetIndex); } / ** *構造函數 * @param路徑導入文件對象 * @param headerNum標題行號標題行號(stringutils.isblank(filename)){拋出新的RunTimeException(“導入文檔為空! ”); } else if(filename.tolowercase()。endswith(“ xls”)){this.wb = new hssfworkbook(is); } else if(filename.tolowercase()。endswith(“ xlsx”)){this.wb = new xssfworkbook(is); } else {拋出新的RunTimeException(“文檔格式不正確!”); } if(this.wb.getnumberofsheets()<SheetIndex){拋出新的RuntimeException(“'文檔中沒有工作表!”); } this.sheet = this.wb.getSheetat(SheetIndex); this.headernum = headernum; log.debug(“初始化成功。”); } / ** *獲取行對象 * @param rownum * @return * / public row getrow(int rownum){return this.sheet.getrow(rownum); } / ** *獲取數據行號 * @return * / public int int getDatarownum(){return headerNum+1; } / ** *獲取最後一個數據行號 * @return * / public int int getlastDatarownum(){return this.sheet.getLastrontum()+headerNum; } / ** *獲取最後一個列號 * @return * / public int int getlastCellnum(){return this.getrow(headerNum).getLastCellnum(); } / ** *獲取單元格值 * @param row獲取的行 * @param列 * @return單元格值 * / public object getCellvalue(row row,int colund){object val =“”;嘗試{cell = row.getCell(column); if(cell!= null){if(cell.getCelltype()== cell.cell_type_numeric){val = cell.getNumericCellValue(); } else if(cell.getCellType()== cell.cell_type_string){val = cell.getStringCellValue(); } else if(cell.getCellType()== cell.cell_type_formula){val = cell.getCellformula(); } else if(cell.getCellType()== cell.cell_type_boolean){val = cell.getBooleanCellValue(); } else if(cell.getCellType()== cell.cell_type_error){val = cell.getErrorCellValue(); }}} catch(異常E){return val; }返回val; } / ** *獲取導入數據列表 * @param cls導入對像類型 * @param組導入分組 * / public <e> list <e> getDatalist(class <e> cls,int ...組)拋出InstantiationException,IllegalAccessexception,illegalAccessexception {list <object <object []> notationlist = lists.newarraylistss.newarraylist() //獲取註釋字段[] fs = cls.getDeclaredFields(); for(field f:fs){expelfield ef = f.getAnnotation(excelfield.class); if(ef! = null &&(ef.type()== 0 || ef.type()== 2)){if(groups!= null && groups.length> 0){boolean ingroup = false; for(int g:groups){if(indroup){break; } for(int efg:ef.groups()){if(g == efg){indroup = true; AnnotationList.Add(new Object [] {EF,F});休息; }}}} else {annotationList.add(new Object [] {Ef,f}); }}} //獲取註釋方法[] ms = cls.getDeclaredMethods(); for(方法m:ms){excelfield ef = m.getantation(excelfield.class); if(ef!= null &&(ef.type()== 0 || ef.type()== 2)){if(groups!= null && groups.length> 0){boolean ingroup = false; for(int g:groups){if(indroup){break; } for(int efg:ef.groups()){if(g == efg){indroup = true; AnnotationList.Add(new Object [] {EF,M});休息; }}}} else {annotationList.add(new Object [] {Ef,m}); }}} //字段排序collections.sort(AnnoTationList,new Comparator <對象[]>(){public int actare comparare(object [] o1,object [] o2){return new new Integer(((Excelfield)O1 [0])。 //log.debug("import列計數:“+annotationList.size()); //獲取excel數據列表<e> datalist = lists.newarraylist(); for(int i = this.getDatarownum(); i <this.getLastDatarownum(); i ++){e e =(e)cls.newinstance(); int列= 0;行行= this.getrow(i); StringBuilder SB = new StringBuilder(); for(object [] OS:AnnotationList){對象val = this.getCellValue(row,column ++); if(val! = null){excelfield ef =(excelfield)OS [0]; //如果是dict類型,請獲得dict值,如果(stringutils.isnotblank(ef.dicttype())){val = dictutils.getDictValue(val.tostring(),ef.dicttype(),ef.dicttype(),“); //log.debug(“dictionary類型值:[“+i+”,“+colunm+”]+val); } //獲取param類型和類型cast class <? > valtype = class.class; if(os [1]實例field){valtype =((field)OS [1])。 getType(); } else if(os [1] instanceof方法){方法方法=((方法)OS [1]); if(“ get” .equals(method.getName()。子字符串(0,3))){valtype = method.getReturntype(); } else if(“ set” .equals(method.getName()。子字符串(0,3))){valtype =((方法)OS [1])。 getParameterTypes()[0]; }} //log.debug("Import值類型:[“+i+”,“+column+”]”+valtype);嘗試{if(valtype == string.class){字符串s = string.valueof(val.tostring()); if(stringutils.endswith(s,“ .0”)){val = stringutils.substringbefore(s,“ .0”); } else {val = string.valueof(val.tostring()); }} else if(valType == integer.class){val = double.valueof(val.tostring())。 intvalue(); } else if(valtype == long.class){val = double.valueof(val.tostring())。 longValue(); } else if(valtype == double.class){val = double.valueof(val.tostring()); } else if(valtype == float.class){val = float.valueof(val.tostring()); } else if(valtype == date.class){val = dateutil.getjavadate(((double)val); } else {if(ef.fieldtype()!= class.class){val = ef.fieldtype()。getMethod(“ getValue”,string.class).invoke(null,val.tostring()); } else {val = class.forname(this.getClass()。getName()。replaceAll(this.getClass()。getSimplename(),“ fieldType。”+valtype.getSimplename()+“ type”)。 }}}} catch(exception ex){log.info(“獲取單元格值[+i+”,“+column+”] error:”+ex.toString()); val = null; } //設置實體值,如果(OS [1] instance of Field){felffions.invokesetter(e,(field)OS [1])。getName(),val); } else if(os [1]實例方法){字符串mthodname =((方法)OS [1])。getName(); if(“ get” .equals(mthodname.substring(0,3))){mthodname =“ set”+stringutils.substringafter(mthodname,“ get”); } ifflections.invokemethod(e,mthodname,new class [] {valtype},new Object [] {val}); }} sb.Append(val+“,”); } datalist.add(e); log.debug(“讀取成功:[“+i+”]”+sb.tostring()); }返回數據師; }}}導入測試
public static void main(string [] args)拋出可投擲{importExcel ei = new importExcel(“ target/export.xlsx”,1); for(int i = ei.getDatarownum(); i <ei.getLastDatarownum(); i ++){row row = ei.getrow(i); for(int j = 0; j <ei.getLastCellnum(); j ++){object val = ei.getCellvalue(row,j); system.out.print(val+“,”); } system.out.print(“/n”); }}}