文件导入导出必须代码
ExportExcel.java
/*** Copyright © 2012-2014 <a href = "https://github.com/thinkgem/jeesite"> Jeesite </a> Todos os direitos reservados. */pacote com.thinkgem.jeesite.common.utils.excel; importar java.io.filenotfoundException; importar java.io.fileOutputStream; importar java.io.ioException; importar java.io.outputStream; importar java.lang.reflect.fiell; import java.lang.reflect.method; import java.TeT.Decalform; java.util.comparator; importar java.util.date; importar java.util.hashmap; importar java.util.linkedhashmap; importar java.util.list; importar java.util.map; importar javax.servlet.http.httpServletResponse; importar org.apache.commons.lang3.stringUtils; importar org.apache.poi.ss.usermodel.cell; importar org.apache.poi.ss.usermodel.cellstyle; import org.apache.poi.ss.s.s.usermermermermerm.d.dAmaty.pache.poii.poi.ss. org.apache.poi.ss.usermodel.font; importar org.apache.poi.ss.usermodel.indexedColors; importar org.apache.poi.ss.usermodel.row; importecache.apache.poi.s.sermodel.sheet.; org.apache.poi.ss.util.cellrangeAddress; importar org.apache.poi.xssf.streaming.sxssfworkbook; importar org.apache.poi.xssf.usermodel.xsflientanchor; import org.apache.poii.xsf.xssflientanchor; import org.apache.poii.xsf.xsflientanchor; org.slf4j.logger; importar org.slf4j.loggerFactory; importar com.google.common.collect.lists; importar com.thinkgem.jeesite.common.utils.dateutils; importar com.thinkgem.jeesite.common.utils.encodes; importar com.thinkgem.jeesite.common.utils.reflections; com.thinkgem.jeesite.common.utils.excel.annotation.excelfield; import com.thinkgem.jeesite.modules.sys.utils.dictutils; /** * 导出 Excel 文件 (导出 “xlsx” 格式 , 支持大数据量导出 @see org.apache.poi.ss.spreadSheetversion) * @author thinkGem * @version 2013-04-21 */public class Class ExportExcel {private statics logger Log = LoggerFactory.getLogger (Exports ExportExcel. / ** * 工作薄对象 */ privado sxssfworkbook wb; / ** * 工作表对象 */ folha privada; / ** * 样式列表 */ mapa privado <String, CellStyle> Styles; / ** * 当前行号 */ private int rownum; /** * 注解列表 (Object [] {Excelfield, campo/método}) */list <object []> anoTationList = lists.newArrayList (); / ** * 字段 mapa */ LinkedHashMap <String, String> FieldMap; Hashmap <string, string> dicttypes; / ** * 构造函数 * @param título 表格标题 , 传 “空值” , 表示无标题 * @param cls 实体对象 , 通过 anotação.exportfield 获取标题 */ public exportExcel (título da string, classe <?> Cls) {this (title, cls, 1); } / ** * 构造函数 * @param título 表格标题 , 传 “空值” , 表示无标题 * @param fieldmap , 获取要导出的字段和字段标题 * / public exportExcel (título da string, LinkedHashmap <string, string> fieldMap) {this.fieldMap = fieldmap; dicttypes = novo hashmap <string, string> (); // inicialize int colunm = 0; List <String> headerList = lists.newArrayList (); para (chave de string: 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); } inicializar (título, headerlist); } / ** * 构造函数 * @param título 表格标题 , 传 “空值” , 表示无标题 * @param cls 实体对象 , 通过 anotação.exportfield 获取标题 * @param tipo 导出类型 (1: 导出数据; 2: 导出模板)) * @param grupos 导入分组 * / public exportExcel (título da string, 导出数据; 导出模板 导出模板)) @Param BURADS 导入分组 * / public ExportExcel (string, [ @] field). cls.getDecLaredFields (); para (Campo F: FS) {Excelfield ef = f.getannotation (Excfelield.class); if (ef! = null && (ef.Type () == 0 || ef.Type () == tipo)) {if (grupos! for (int g: grupos) {if (ingroup) {break; } para (int efg: ef.groups ()) {if (g == efg) {ingrup = true; anoTationList.add (novo objeto [] {ef, f}); quebrar; }}}} else {annotationList.add (novo objeto [] {ef, f}); }}} // Obtenha método de anotação [] ms = cls.getDecLaredMethods (); for (método m: ms) {Excelfield ef = m.getannotation (Excfelfield.class); if (ef! = null && (ef.Type () == 0 || ef.Type () == tipo)) {if (grupos! for (int g: grupos) {if (ingroup) {break; } para (int efg: ef.groups ()) {if (g == efg) {ingrup = true; anoTationList.add (novo objeto [] {ef, m}); quebrar; }}}} else {AnoTationList.add (novo objeto [] {ef, m}); }}} // Coleções de classificação de campo // Lista inicialize <String> headerList = lists.newArrayList (); for (objeto [] os: anoTationList) {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); } inicializar (título, headerlist); } / ** * 构造函数 * @param título 表格标题 , 传 “空值” , 表示无标题 * @param cabeçalhos 表头数组 * / public exportExcel (título da string, string [] cabeçalhos) {Initialize (title, lists.newArrayList (cabeçalhos)); } / ** * 构造函数 * @param título 表格标题 , 传 “空值” , 表示无标题 * @param headerlist 表头列表 * / public exportExcel (título da string, list <string> headerList) {inicialize (title, headerlist); } / ** * 初始化函数 * @param título 表格标题 , 传 “空值” , 表示无标题 * @param headerlist 表头列表 * / private void inicialize (título da string, list <string> headerList) {this.wb = new SXSSFWorkbook (500); this.sheet = wb.createSheet ("export"); this.styles = createStyles (WB); // Crie título if (stringUtils.isnotblank (title)) {linha titlerow = sheet.crerowerow (rownum ++); titlerow.SethEightInPoints (30); Celular titleCell = titlerow.createCell (0); titleCell.setCellStyle (styles.get ("title")); titleCell.setCellValue (título); Sheet.AddmergedRegion (New CellRangeAddress (titlerow.getrownum (), titlerow.getrownum (), titlerow.getrownum (), headerlist.size ()-1)); } // Crie cabeçalho if (headerlist == null) {lança nova run timeException ("headerlist não nulo!"); } Linha headerrow = sheet.crerowroow (rownum ++); headerrow.setheightinpoints (16); for (int i = 0; i <headerlist.size (); i ++) {célula celular = headerrow.createCell (i); Cell.setCellStyle (Styles.get ("Header")); String [] ss = stringUtils.split (headerlist.get (i), "**", 2); if (ss.Length == 2) {Cell.SetCellValue (SS [0]); Comentário comentário = this.sheet.createdrawingpatriarch (). CreateCellComment (novo xssfclientanchor (0, 0, 0, 0, (curto) 3, 3, (curto) 5, 6)); comentário.SetString (novo xssfrichtextString (ss [1])); Cell.setCellComment (Comentário); } else {Cell.SetCellValue (headerlist.get (i)); } Sheet.Autosizecolumn (i); } para (int i = 0; i <headerlist.size (); i ++) {int colwidth = sheet.getColumnWidth (i)*2; Sheet.setColumnWidth (i, Colwidth <3000? 3000: Colwidth); } log.debug ("Inicialize sucesso"); } / ** * 创建表格样式 * @param wb 工作薄对象 * @return 样式列表 * / mapa privado <string, CellStyle> Creatrestyles (pasta de trabalho wb) {map <string, célula> styles = new hashmap <string, célula> (); CellStyle Style = WB.CreateCellStyle (); style.Setalignment (CellStyle.align_center); style.setverticalAlignment (CellStyle.vertical_center); Font titlefont = wb.createFont (); titlefont.setFontName ("Arial"); titlefont.setFoTheightInPoints ((curta) 16); titlefont.setBoldweight (Font.Boldweight_bold); style.setFont (titleFont); styles.put ("title", estilo); estilo = wb.createCellStyle (); style.setverticalAlignment (CellStyle.vertical_center); style.setBorderright (CellStyle.Border_thin); style.setLrightDorDerColor (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.setFoTheightInPoints ((curta) 10); style.setFont (DataFont); styles.put ("dados", estilo); estilo = wb.createCellStyle (); style.cloneStylefrom (styles.get ("dados")); style.selignment (CellStyle.align_left); styles.put ("data1", estilo); estilo = wb.createCellStyle (); style.cloneStylefrom (styles.get ("dados")); style.Setalignment (CellStyle.align_center); styles.put ("data2", estilo); estilo = wb.createCellStyle (); style.cloneStylefrom (styles.get ("dados")); style.Setalignment (CellStyle.align_right); styles.put ("data3", estilo); estilo = wb.createCellStyle (); style.cloneStylefrom (styles.get ("dados")); // style.setWrapText (true); style.Setalignment (CellStyle.align_center); style.setFillForeRoundColor (indexedColors.grey_50_Percent.getIndex ()); style.setFillPattern (CellStyle.solid_foreground); Font headerfont = wb.createFont (); headerfont.setFontName ("Arial"); headerfont.setFoTheightInPoints ((curta) 10); headerfont.setBoldweight (Font.Boldweight_bold); headerfont.setColor (indexedColors.white.getIndex ()); style.setFont (Headefont); styles.put ("cabeçalho", estilo); estilos de retorno; } / ** * 添加一行 * @return 行对象 * / public line addRow () {return sheet.crerower (rownum ++); } / ** * 添加一个单元格 * @param linha 添加的行 * @param coluna 添加列号 * @param val 添加值 * @return 单元格对象 * / public célula addcell (linha de linha, int coluna, objeto val) {return this.addcell (linha, coluna, val, 0, class.class); } / ** * 添加一个单元格 * @param linha 添加的行 * coluna @param 添加列号 * @param val 添加值 * @param align 对齐方式 (1: 靠左; 2 : 居中; 3: 靠右)) * @return 单元格对象 * / public Cell Addcell (linha da linha, int, val, int alinhado, classe <> campo (campo) {linha de linha; CellStyle Style = Styles.get ("Data"+(alinhe> = 1 && alinhe <= 3? Alinhe: "")); tente {if (val == null) {Cell.setCellValue (""); } else if (valt instanceof string) {Cell.setCellValue ((String) val); } else if (Val instanceof integer) {Cell.setCellValue ((Integer) val); } else if (valt instanceof long) {Cell.setCellValue ((Long) val); } else if (Val instanceof duplo) {Cell.setCellValue (new DecimalFormat (". #####"). formato (val)); } else if (Val instanceof float) {Cell.setCellValue (((float) val); } else if (Val instanceOf date) {DataFormat format = wb.createTataFormat (); 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 (). replaceall (this.getclass (). getSpleName (), "fieldType."+val.getClass (). getSplename ()+"tipo"). }}} catch (Exceção ex) {log.info ("Defina o valor da célula ["+row.getRownum ()+","+coluna+"] erro:"+ex.toString ()); Cell.SetCellValue (val.toString ()); } Cell.setCellStyle (estilo); célula de retorno; } / ** * 添加数据 (通过 AnoTation.ExportField 添加数据)) @Return List 数据列表 * / public <E> exportExcel setDatalist (List <E> List) {for (e e: list) {int colunm = 0; Linha da linha = this.addrow (); Stringbuilder sb = new stringbuilder (); if (e instanceof map) {@suppresswarnings ("desmarcado") mapa <string, objeto> map = (map <string, object>) e; para (chave da string: fieldmap.keyset ()) {objeto value = map.get (key); String columnDictType = dicttypes.get (colunm+""); if (stringUtils.isnotblank (columnDictType)) {value = dictutils.getDictLabel (value == null? "": value.toString (), columnDictType, ""); } this.addcell (linha, colunm ++, value == null? "": value.toString (), 0, string.class); sb.append (valor + ","); }} else {for (object [] OS: AnoTationList) {Excelfield ef = (Excelfield) OS [0]; Objeto val = null; // obtenha o valor da entidade, tente {if (stringUtils.isnotblank (ef.Value ())) {val = reflexões.invokegetter (e, ef.Value ()); } else {if (os [1] instanceof Field) {val = reflectionS.inVokeGetter (e, (((campo) OS [1]). getName ()); } else if (os [1] Instância do método) {val = reflexões.invokemethod (e, (((método) os [1]). getName (), nova classe [] {}, new Object [] {}); }} // Se for ditado, obtenha o rótulo do ditado se (stringUtils.isnotblank (ef.dicttype ())) {val = dictutils.getdictlabel (val == null? "": Val.toString (), ef.dicttype (), ""); }} catch (Exceção ex) {// falha em ignorar log.info (ex.toString ()); val = "" "; } this.addcell (linha, colunm ++, val, ef.align (), ef.fieldType ()); sb.append (val + ","); } log.debug ("Escreva sucesso: ["+row.getrownum ()+"]"+sb.toString ()); }} Retorne isso; } / ** * 输出数据流 * @param os 输出数据流 * / public exportExcel write (outputStream OS) lança IoException {WB.Write (OS); devolver isso; } / ** * 输出到客户端 * @param FileName 输出文件名 * / public exportexcel write (httpServletResponse resposta, string filename) lança IoException {Response.Reset (); Response.setContentType ("Application/Octet-Stream; Charset = UTF-8"); Response.setheader ("Content-Disposition", "Applement; filename ="+codes.urlencode (nome do arquivo)); write (resposta.getOutputStream ()); devolver isso; } / ** * 输出到文件 * @param FileName 输出文件名 * / public exportexcel writefile (nome da string) lança fileNotfoundException, ioexception {FileOutputStream OS = new FileOutputStream (nome); this.Write (OS); devolver isso; } / ** * 清理临时文件 * / public exportExcel Dispon () {wb.dispose (); devolver isso; }}导出测试
public static void main (string [] args) lança arremesso {list <string> headerList = lists.newArrayList (); for (int i = 1; i <= 10; i ++) {headerlist.add ("表头"+i); } List <string> dataarowlist = lists.newArrayList (); for (int i = 1; i <= headerlist.size (); i ++) {dataarowlist.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 ++) {linha linha = ee.addrow (); for (int j = 0; j <datalist.get (i) .size (); j ++) {ee.addcell (linha, j, datalist.get (i) .get (j)); }} ee.writefile ("Target/export.xlsx"); ee.dispose (); log.debug ("Sucesso de exportação"); }ImportExcel.java
/*** Copyright © 2012-2014 <a href = "https://github.com/thinkgem/jeesite"> Jeesite </a> Todos os direitos reservados. */pacote com.thinkgem.jeesite.common.utils.excel; importar java.io.file; importar java.io.fileInputStream; importar java.io.ioException; importar java.io.inputStream; importar java.lang.reflect.field; import java.lang.reflect.method; import.Util.AlTevAvador Java.reflect.method; importar; java.util.list; import org.apache.commons.lang3.StringUtils;import org.apache.poi.hssf.usermodel.HSSFWorkbook;import org.apache.poi.openxml4j.exceptions.InvalidFormatException;import org.apache.poi.ss.usermodel.Cell;import org.apache.poi.ss.usermodel.dateutil; importar org.apache.poi.ss.usermodel.row; importar org.apache.poi.ss.usermodel.msheet; importesterfache.apache.poi.s.UsermorMworksbook; importação.terfache.pache.apache.poi.s.UsermorMworks; org.slf4j.logger; importar org.slf4j.loggerFactory; importar org.springframework.web.multipart.multipartFile; importar com.google.common.collect.lists; importar com.thinkgem.jeesite.common.utils.reflections; importação com.thinkgem.jeesite.common.utils.excel.annotation.excelfield; import.thinkgem.jeesite.modules.sytils.gils.diltut; /** * 导入 Excel 文件 (支持 “xls” 和 “xlsx” 格式) * @author ThinkGem * @version 2013-03-10 */public classe importExcel {private static logger log = loggerFactory.getLogger (importexcel.class); / ** * 工作薄对象 */ pasta de trabalho privada WB; / ** * 工作表对象 */ folha privada; / ** * 标题行号 */ private int headernum; / ** * 构造函数 * @param Path 导入文件 , 读取第一个工作表 * @param headrernum 标题行号 , 数据行号 = 标题行号 +1 * @throws invalidformatexception * @throws ioexception */ public importExcel (string filename, internum) lança inválido hetexception, ioException {this (novo arquivo (arquivo (arquivo (arquivo), names), lança inválido para a cabeça, ioxception (this (new Filsename), } / ** * 构造函数 * @param Path 导入文件对象 , 读取第一个工作表 * @param headernum 标题行号 , 数据行号 = 标题行号 +1 * @throws InvalidFormatexception * @THOWSoxException * / public ImportExcel (arquivo de arquivo, INTRERNUM) lança inválido } /** * 构造函数 * @param path 导入文件 * @param headerNum 标题行号,数据行号=标题行号+1 * @param sheetIndex 工作表编号 * @throws InvalidFormatException * @throws IOException */ public ImportExcel(String fileName, int headerNum, int sheetIndex) throws InvalidFormatException, IOException { this(new File(fileName), headerNum, sheetIndex); } / ** * 构造函数 * @Param Path 导入文件对象 * @param headrernum 标题行号 , 数据行号 = 标题行号 +1 * @param SheetIndex 工作表编号 * @ThRows InvalidFormatexception * @THOWSOWSCECCETION * / public ImportExcel (arquivo Int Headnum, intInDIndEx) THROWSENEMEMEMEMEMEXEXCEMCEXCELECCECCENCENTE (FILHE, Int Headnum, Int (IntInDIndEx) Headernum, SheetIndex); } / ** * 构造函数 * Arquivo @param 导入文件对象 * @param headernum 标题行号 , 数据行号 = 标题行号 +1 * @param SheetIndex 工作表编号 * @ThRows InvalidFormatexception * @THOWSOWSCECTIONS * / Public ImportExcexcembel (MultipartFile FilutFile, Int HeadRernum, IntIndex) este (multipartfile.getoriginalfilename (), multipartfile.getInputStream (), headernum, SheetIndex); } / ** * 构造函数 * @param Path 导入文件对象 * @param headrernum 标题行号 , 数据行号 = 标题行号 +1 * @param SheetIndex 工作表编号 * @THOWS INVALIDFORMATEXCECTION * @THOWSECTIONS IOException * / public ImportExcel (String FileName, InputStream, Int i HeadRernum, intIndex) SlowSidEx. (Stringutils.isblank (nome do arquivo)) {tiro o novo RUNTimeException ("导入文档为空!"); } else if (filename.tolowerCase (). endswith ("xls")) {this.wb = new HSSFWorkbook (IS); } else if (filename.tolowercase (). endswith ("xlsx")) {this.wb = new XSSFWorkbook (IS); } else {lança a nova RunTimeException ("文档格式不正确!"); } if (this.wb.getNumberOfSheets () <SheetIndex) {lança nova RuntimeException ("文档中没有工作表!"); } this.sheet = this.wb.getSheetat (SheetIndex); this.Headernum = Headernum; log.debug ("Inicialize o sucesso."); } / ** * 获取行对象 * @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 linha 获取的行 * coluna @param 获取单元格列号 * @return 单元格值 * / objeto público getCellValue (linha da linha, int coluna) {objeto val = ""; tente {célula celular = row.getCell (coluna); if (célula! = 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 (Exceção e) {return val; } retornar val; } / ** * 获取导入数据列表 * @param cls 导入对象类型 * @param Grupos 导入分组 * / public <E> List <E> getDatalist (classe <e> cls, int ... grupos) lança instantaçãoException, ilegalacceSexception {list <object []> anoTationList = lists.NewArrayList (); // Obtenha campo de anotação [] fs = cls.getDecLaredFields (); para (Campo F: FS) {Excelfield ef = f.getannotation (Excfelield.class); if (ef! = null && (ef.Type () == 0 || ef.Type () == 2)) {if (grupos! for (int g: grupos) {if (ingroup) {break; } para (int efg: ef.groups ()) {if (g == efg) {ingrup = true; anoTationList.add (novo objeto [] {ef, f}); quebrar; }}}} else {annotationList.add (novo objeto [] {ef, f}); }}} // Obtenha método de anotação [] ms = cls.getDecLaredMethods (); for (método m: ms) {Excelfield ef = m.getannotation (Excfelfield.class); if (ef! = null && (ef.Type () == 0 || ef.Type () == 2)) {if (grupos! for (int g: grupos) {if (ingroup) {break; } para (int efg: ef.groups ()) {if (g == efg) {ingrup = true; anoTationList.add (novo objeto [] {ef, m}); quebrar; }}}} else {AnoTationList.add (novo objeto [] {ef, m}); }}} // Coleções de classificação de campo //log.debug("import colunas contagem de colunas: "+anoTationList.size ()); // Get Excel Data List <E> DATALIST = LISTS.NEWARRAYLIST (); for (int i = this.getDatarownum (); i <this.getLastDatarownum (); i ++) {e e = (e) cls.newInstance (); Int coluna = 0; Linha linha = this.getRow (i); Stringbuilder sb = new stringbuilder (); para (objeto [] OS: AnoTationList) {objeto val = this.getCellValue (linha, coluna ++); if (val! = null) {Excelfield ef = (Excelfield) os [0]; // Se for o tipo ditado, obtenha o valor do ditado se (stringUtils.isnotblank (ef.dicttype ())) {val = dictutils.getDictValue (val.tostring (), ef.dicttype (), ""); //log.debug("Dictionary Type Valor: ["+i+", "+colunm+"] "+val); } // obtenha o tipo de param e tipo de classe de elenco <?> Valtype = classe.class; if (os [1] instância do campo) {valtype = ((campo) os [1]). getType (); } else if (OS [1] Instância do método) {Método Método = ((Método) OS [1]); if ("get" .equals (métod.getName (). Substring (0, 3))) {valtype = method.getrendrtype (); } else if ("set" .equals (métod.getName (). Substring (0, 3))) {valtype = ((método) os [1]). getParameterTypes () [0]; }} //log.debug("Import Type: ["+i+", "+coluna+"] "+valtype); tente {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 = duplo.valueof (val.toString ()). intvalue (); } else if (valtype == long.class) {val = duplo.valueof (val.toString ()). longValue (); } else if (valtype == duplo.class) {val = duplo.valueof (val.toString ()); } else if (valtype == float.class) {val = float.valueof (val.toString ()); } else if (valtype == date.class) {val = dateutil.getjavadate ((duplo) 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 ()+"tipo"). }}} catch (Exceção ex) {log.info ("Get Cell Value ["+i+","+coluna+"] erro:"+ex.toString ()); val = nulo; } // Defina o valor da entidade if (OS [1] Instância de campo) {reflexões.inVokesetter (e, ((campo) OS [1]). getName (), val); } else if (OS [1] Instância do método) {String mthodName = ((Method) OS [1]). getName (); if ("get" .equals (mthodname.substring (0, 3))) {mthodname = "set"+stringUtils.substringafter (mthodname, "get"); } Reflexões.invokemethod (e, mthodname, nova classe [] {valtype}, novo objeto [] {val}); }} sb.append (val+","); } datalist.add (e); log.debug ("Leia o sucesso: ["+i+"]"+sb.toString ()); } retornar datalist; }}导入测试
public static void main (string [] args) lança lançável {importExcel EI = new ImportExcel ("Target/Export.xlsx", 1); for (int i = ei.getDatarownum (); i <ei.getLastDatarownum (); i ++) {linha linha = ei.getRow (i); for (int j = 0; j <ei.getLastCellnum (); j ++) {objeto val = ei.getCellValue (linha, j); System.out.print (val+","); } System.out.print ("/n"); }}