文件导入导出必须代码
Exportexcel.java
/*** Copyright©2012-2014 <a href = "https://github.com/thinkgem/jeesite"> jeesite </a>すべての権利は留保されています。 */パッケージcom.thinkgem.jeesite.common.utils.excel; java.io.fileenotfoundexception; Import java.io.fileoutputStream; Import java.io.ioexception; Import java.io.outputStream; Import java.lang.reflect.field; Import java.lang.reflt.method; Import Java.text.decimalformat java.util.comparator; import java.util.date; Import java.util.hashmap; Import java.util.linkedhashmap; Import java.util.list; import 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.sermodel.cellstyle; Import org.apache.poi.ss.usermodel.comment; Import org.poi.ss.s.s.susermodel.data org.apache.poi.ss.usermodel.Font;import org.apache.poi.ss.usermodel.IndexedColors;import org.apache.poi.ss.usermodel.Row;import org.apache.poi.ss.usermodel.Sheet;import org.apache.poi.ss.usermodel.Workbook;import apache.poi.ss.util.cellrangeaddress; Import org.apache.poi.xssf.streaming.sxssfworkbook; Import org.apache.poi.xssf.usermodel.xssfclientanchor; org.apache.xssf.usermodel.xssssssssssssf. org.slf4j.logger; import org.slf4j.loggeractory; com.google.common.collect.lists;インポートcom.thinkgem.jeesite.common.utils.dateutils; Import com.thinkgem.jeesite.common.utils.encodes; 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 文件(导出“ xlsx”格式、支持大数据量导出@see org.apache.poi.ss.sssheetversion / ** *工作薄对象 */ private sxssfworkbook wb; / ** *工作表对象 */プライベートシートシート。 / ** *样式列表 */プライベートマップ<文字列、CellStyle> Styles; / ** *当前行号 */ private int rownum; /** * 注解列表( object [] {Excelfield、field/method}) */list <object []> annotationlist = lists.newarraylist(); / ** *字段マップ */ linkedhashmap <string、string> fieldmap; hashmap <string、string> dicttypes; / ** *构造函数 * @param Title表格标题、传 "空值”、表示无标题 * @param cls实体对象、通过annotation.exportfield获取标题 */ public exportexcel(string title、class <?> cls){this(title、cls、1); } / ** *构造函数 * @param title表格标题、传 "空值”、表示无标题 * @param fieldmap、获取要导出的字段和字段标题 * / public exportexcel(string title、linkedhashmap <string、string> fieldmap){this.fieldmap = fieldmap; dicttypes = new Hashmap <String、String>(); // int colunm = 0を初期化します。 List <String> headerList = lists.newArrayList(); for(string key:fieldmap.keyset()){string 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( "dicttype")!= null){dicttypes.put( ""+(colunm)、map.get( "dicttype")); } colunm ++; headerlist.add(t); } initialize(title、headerList); } / ** *构造函数 * @param Title表格标题、传、「空值」、表示无标题 * @param cls实体对象、通过annotation.exportfield获取标题 * @param Type cls.getdeclaredfields(); for(field f:fs){excelfield ef = f.getannotation(excelfield.class); if(ef!= null &&(ef.type()== 0 || ef.type()== type)){if(groups!= null && groups.length> 0){boolean group = false; for(int g:groups){if(group){break; } for(int efg:ef.groups()){if(g == efg){ingroup = true; annotationlist.add(new object [] {ef、f});壊す; }}}} else {annotationlist.add(new object [] {ef、f}); }}} // get annotation method [] ms = cls.getDeclaredMethods(); for(方法m:ms){excelfield ef = m.getannotation(excelfield.class); if(ef!= null &&(ef.type()== 0 || ef.type()== type)){if(groups!= null && groups.length> 0){boolean group = false; for(int g:groups){if(group){break; } for(int efg:ef.groups()){if(g == efg){ingroup = true; annotationList.add(new object [] {ef、m});壊す; }}}} else {annotationlist.add(new object [] {ef、m}); }}} //フィールドソートコレクション(annotationlist、new Comparator <object []>(){public int compare(object [] o1、object [] o2){return new Integer(((excelfield)o1 [0])。 //リスト<String> headerList = lists.newArrayList(); for(object [] os:annotationlist){string t =((excelfield)os [0])。title(); //如果是导出、则去掉注释if(type == 1){string [] ss = stringutils.split(t、 "**"、2); if(ss.length == 2){t = ss [0]; }} headerlist.add(t); } initialize(title、headerList); } / ** *构造函数 * @param title表格标题、传 "空值”、表示无标题 * @paramヘッダー表头数组 * / public exportexcel(string title、string [] headers){initialize(title、lists.newarraylist(headers)); } / ** *构造函数 * @param Title表格标题、传“”、表示无标题 * @param headerlist表头列表 * / public exportexcel(string title、list <string> headerlist){initialize(title、headerlist); } / ** *初始化函数 * @param Title表格标题、传 "空值”、表示无标题 * @param headerlist表头列表 * / private void initialize(string title、list <string> headerlist){this.wb = new sxssfworkbook(500); this.sheet = wb.createsheet( "Export"); this.styles = createstyles(wb); //タイトルを作成するif(stringutils.isnotblank(title)){row titlerow = sheet.createrow(rownum ++); titlerow.setheightinpoints(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)); } //ヘッダーを作成するif(headerlist == null){new new runtimeException( "headerList Not Null!"); } row headerrow = sheet.createrow(rownum ++); headerrow.setheightinpoints(16); for(int i = 0; i <headerlist.size(); i ++){cell 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、(Short)3、3、(Short)5、6)); comment.setString(new 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( "initialize success。"); } / ** *创建表格样式 * @param wb CellStyle Style = wb.CreateCellStyle(); style.setalignment(cellstyle.align_center); style.setverticalAlignment(cellstyle.vertical_center); font titlefont = wb.createfont(); titlefont.setfontname( "arial"); titlefont.setfontheightinpoints((short)16); titlefont.setboldweight(font.boldweight_bold); style.setfont(titlefont); styles.put( "title"、style); 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.setbottombordercolor(indexedColors.grey_50_percent.getIndex()); font datafont = wb.createfont(); dataFont.setFontName( "arial"); datafont.setfontheightinpoints((short)10); style.setfont(dataFont); styles.put( "data"、style); style = wb.createcellstyle(); style.clonestylefrom(styles.get( "data")); style.setalignment(cellstyle.align_left); styles.put( "data1"、style); style = wb.createcellstyle(); style.clonestylefrom(styles.get( "data")); style.setalignment(cellstyle.align_center); styles.put( "data2"、style); style = wb.createcellstyle(); style.clonestylefrom(styles.get( "data")); style.setalignment(cellstyle.align_right); styles.put( "data3"、style); 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); font headerfont = wb.createfont(); headerfont.setFontName( "arial"); headerfont.setfontheightinpoints((short)10); headerfont.setboldweight(font.boldweight_bold); headerfont.setColor(indexedColors.white.getIndex()); style.setfont(headerfont); styles.put( "header"、style);リターンスタイル; } / ** *添加一行 * @return行对象 * / public row addrow(){return sheet.createrow(rownum ++); } / ** *添加一个单元格 * @param row添加的行 * @param列添加列号 * @param val添加值 * @return单元格对象 * / public cell addcell(row row、int column、object val){return this.addcell(row、column、val、0、class.class); } / ** *添加一个单元格 * @param row添加的行 * @param列添加列号 * @param val添加值 * @param align 对齐方式( 1:靠左; 2:居中; 3:靠右) * @return单元格对象 * / public cell addcell(row row、int column、int align、int align、class <?> fieldtype) CellStyle Style = styles.get( "data"+(align> = 1 && align <= 3?align: "")); try {if(val == null){cell.setCellValue( ""); } else if(val instanceof string){cell.setCellValue(((string)val); } else if(val instanceof integer){cell.setCellValue((integer)val); } else if(val instanceof long){cell.setcellvalue((long)val); } else if(val instanceof double){cell.setCellValue(new DecimalFormat( "。#####")。format(val)); } else if(val instanceof float){cell.setcellvalue((float)val); } else if(val instanceof date){dataformat format = 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値["+row.getRownum()+"、"+column+"]エラー:"+ex.toString()); cell.setCellValue(val.toString()); } cell.setCellStyle(style);戻りセル。 } / ** * anontation.exportfield 添加数据) * @return list row row = this.addrow(); stringbuilder sb = new StringBuilder(); if(e instanceof map){@suppresswarnings( "unchecked")map <string、object> map =(map <string、object>)e; for(string key:fieldmap.keyset()){object value = map.get(key);文字列columnDictType = dictTypes.get(colunm+""); if(stringutils.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; // Entity値を取得する{if(stringutils.isnotblank(ef.value())){val = reflections.invokegetter(e、ef.value()); } else {if(os [1] instanceof field){val = reflections.invokegetter(e、((field)os [1])。getname()); } else if(os [1] instanceof method){val = reflections.invokemethod(e、((method)os [1])。getname()、new class [] {}、new object [] {}); }} // dict is dict、dict label if(stringutils.isnotblank(ef.dicttype())){val = dictutils.getdictlabel(val == null? "":val.tostring()、ef.dicttype()、 ""); }} catch(Exception ex){// log.info(ex.tostring()); val = ""; } this.addcell(row、colunm ++、val、ef.align()、ef.fieldtype()); sb.append(val + "、"); } log.debug( "write success:["+row.getRownum()+"]"+sb.toString()); }}これを返します。 } / ** *输出数据流 * @param osこれを返します。 } / ** *输出到客户端 * @param filename输出文件名 * / public exportexcel write(httpservletResponse response、string filename)throws ioexception {respons.reset(); Response.setContentType( "Application/Octet-Stream; charset = utf-8"); Response.setheader( "content-disposition"、 "attachment; filename ="+encodes.urlencode(filename));書き込み(Response.getOutputStream());これを返します。 } / ** *输出到文件 * @param filename输出文件名 * / public exportexcel writefile(string name)throws filenotfoundexception、ioexception {fileoutputStream os = new fileoutputStream(name); 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( "Export success。"); }importexcel.java
/*** Copyright©2012-2014 <a href = "https://github.com/thinkgem/jeesite"> jeesite </a>すべての権利は留保されています。 */パッケージcom.thinkgem.jeesite.common.utils.excel; Import java.io.file; Import java.io.fileinputStream; Import java.io.io.ioexception; Import java.io.inputStream; Import java.lang.reflect.field; Import java.lang.reflect.method; import java.util.collections; import java.util.util.comparator; java.util.list; org.apache.commons.lang3.stringutils; Import org.apache.poi.hssf.usermodel.hssfworkbook; Import org.apache.poi.openxml4j.exceptions.invalidformatexception; Import org.apache.poi.s.s.s.sermodel.cell; org.apache.poi.ss.sermodel.dateutil; import org.apache.poi.ss.usermodel.row; Import org.apache.poi.ss.sermodel.sheet; Import org.apache.poi.ss.usermodel.workbook; Import org.apache.poi.xxsf.susf.susf.susf.susf.susf.sf.sf.sf.sf.sf.sf.sf.sf.sf.sf.sf.sf.sf.sf.sf.sf.sf.sf.sf.sf.sf.sf.sf.sf. org.slf4j.logger; Import org.slf4j.loggeractory; Import org.springframework.web.multipart.multipartfile; com.google.common.collect.lists; Import com.thinkgem.jeesite.common.utils.reflection; Import com.thinkgem.jeesite.common.utils.excel.annotation.excelfield; Import com.thinkgem.jeesite.modules.sys.utils.dictils; /** * excel 文件(支持“ xls”和“ xlsx” 格式) * @author thinkgem * @version 2013-03-10 */public class importexcel {private static logger log = loggeractory.getLogger(importexcel.class); / ** *工作薄对象 */プライベートワークブックWB; / ** *工作表对象 */プライベートシートシート。 / ** *标题行号 */ private int headernum; / ** *构造函数 * @Param Path } / ** *构造函数 * @param Path } / ** *构造函数 * @param Path导入文件 * @param headernum } / ** *构造函数 * @param Path Headernum、SheetIndex); } / ** *构造函数 * @param file导入文件对象 * @param headernumこの(multipartfile.getoriginalfilename()、multipartfile.getInputStream()、headernum、sheetindex); } / ** *构造函数 * @param path导入文件对象 * @param headernum (stringutils.isblank(filename)){throw new runtimeexception( "导入文档为空!"); } else if(filename.tolowercase()。endswith( "xls")){this.wb = new hssfworkbook(is); } else if(filename.tolowercase()。endswith( "xlsx")){this.wb = new xssfworkbook(is); } else {throw new runtimeexception( "文档格式不正确!"); } if(this.wb.getNumberOfSheets()<SheetIndex){throw new runtimexcection( "文档中没有工作表!"); } this.sheet = this.wb.getsheetat(sheetindex); this.headernum = headernum; log.debug( "initialize success。"); } / ** *获取行对象 * @param rownum * @return * / public row getrow(int rownum){return this.sheet.getrow(rownum); } / ** *获取数据行号 * @return * / public int getDatarownum(){return headernum+1; } / ** *获取最后一个数据行号 * @return * / public int getLastDatarownum(){return this.sheet.getLastrownum()+headernum; } / ** *获取最后一个列号 * @return * / public int getLastCellnum(){return this.getRow(headernum).getLastCellnum(); } / ** *获取单元格值 * @param row获取的行 * @param列获取单元格列号 * @return单元格值 * / public object getCellValue(row row、int column){object val = ""; try {cell cell = row.getCell(列); 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 // Annotationフィールドを取得します[] fs = cls.getDeclaredfields(); for(field f:fs){excelfield 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(group){break; } for(int efg:ef.groups()){if(g == efg){ingroup = true; annotationlist.add(new object [] {ef、f});壊す; }}}} else {annotationlist.add(new object [] {ef、f}); }}} // get annotation method [] ms = cls.getDeclaredMethods(); for(方法m:ms){excelfield ef = m.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(group){break; } for(int efg:ef.groups()){if(g == efg){ingroup = true; annotationList.add(new object [] {ef、m});壊す; }}}} else {annotationlist.add(new object [] {ef、m}); }}} //フィールドソートコレクション(annotationlist、new Comparator <object []>(){public int compare(object [] o1、object [] o2){return new Integer(((excelfield)o1 [0])。 //log.debug("import column count: "+annotationlist.size()); // Excelデータリストを取得<e> datalist = lists.newarraylist(); for(int i = this.getdatarownum(); i <this.getLastDatarownum(); i ++){e e =(e)cls.newinstance(); int column = 0;行row = this.getrow(i); stringbuilder sb = new StringBuilder(); for(object [] os:annotationlist){object val = this.getCellValue(row、column ++); if(val!= null){excelfield ef =(excelfield)os [0]; // dictタイプの場合、dict値を取得するif(stringutils.isnotblank(ef.dicttype())){val = dictutils.getDictValue(val.toString()、ef.dicttype()、 ""); //log.debug("dictionary Type値:["+i+"、 "+colunm+"] "+val); } //パラマイ型とタイプキャストクラスを取得<?> valtype = class.class; if(os [1] instanceof field){valtype =((field)os [1])。getType(); } else if(os [1] instanceof method){method method =((method)os [1]); if( "get" .equals(method.getname()。substring(0、3))){valtype = method.geturntype(); } else if( "set" .equals(method.getname()。substring(0、3))){valtype =((method)os [1])。getParametertypes()[0]; }} //log.debug("import value type:["+i+"、 "+column+"] "+valtype); try {if(valtype == string.class){string 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()。latearl(this.getClass()。getSimplename()、 "fieldtype。"+valtype.getSimplename()+"type"))。 }}} catch(Exception ex){log.info( "get cell値["+i+"、"+column+"]エラー:"+ex.toString()); val = null; } //エンティティ値を設定if(os [1] instanceof field){reflections.invokesetter(e、((field)os [1])。getname()、val); } else if(os [1] instanceof method){string mthodname =((method)os [1])。getname(); if( "get" .equals(mthodname.substring(0、3)))){mthodname = "set"+stringutils.substringafter(mthodname、 "get"); } reflections.invokemethod(e、mthodname、new class [] {valtype}、new object [] {val}); }} sb.append(val+"、"); } datalist.add(e); log.debug( "read success:["+i+"]"+sb.toString()); }データリストを返します。 }}导入测试
public static void main(string [] args)スロースロー可能{importexcel ei = new importexcel( "ターゲット/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"); }}