文件导入导出必须代码
Exportexcel.java
/*** Copyright © 2012-2014 <a href = "https://github.com/thinkgem/jeesite"> jeesite </a> Todos los derechos reservados. */paquete com.thinkgem.jeesite.common.utils.excel; import java.io.filenotfoundException; import java.io.fileOutputStream; import java.io.ioException; import java.io.outputstream; import java.lang.reflect.field; import java.lang.reflect.method; import java.text.decimalformat; import java.util.util. java.util.comparator; import java.util.date; import java.util.hashmap; import java.util.linkedhashmap; import java.util.list; import java.util.map; import javax.servlet.http.httpservletResponse; importar org.apache.commons.lang3.stringutils; import org.apache.poi.ss.usermodel.cell; importar org.apache.poi.ss.usermodel.cellstyle; importar org.pache.poi.ss.usermodel.comment; import org.apache.ss.ss.usermodel.dataformat; importar; 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 og.apache.ss.usermodel. org.apache.poi.ss.util.cellrangoaddress; import org.apache.poi.xssf.streaming.sxssfworkbook; import org.apache.poi.xssf.usermodel.xssfclientArchor; import org.apache.poi.xssf.usermodel.xssFrichSing; org.slf4j.logger; import org.slf4j.loggerFactory; import com.google.common.collect.lists; import com.thinkgem.jeesite.common.utils.dateutils; import com.thinkgem.jeesite.common.utils.encodes; import com.thinkgem.jeesite.common.utils.esflecciones; com.thinkgem.jeesite.common.utils.excel.annotation.excelfield; import com.thinkgem.jeesite.modules.sys.utils.dictutils; /** * 导出 Excel 文件(导出 “XLSX” 格式 , 支持大数据量导出 支持大数据量导出 @see org.apache.poi.ss.speadsheetversion) * @author thinkgem * @version 2013-04-21 */public class exportExcel {private static log = loggery.getLogger (exportExEx.class); / ** * 工作薄对象 */ private sxssfworkbook wb; / ** * 工作表对象 */ Hoja privada; / ** * 样式列表 */ private Map <String, CellStyle> Styles; / ** * 当前行号 */ private int Rownum; /** * 注解列表( Object [] {ExcEffield, Field/Method}) */List <Object []> AnnotationList = lists.newarrayList (); / ** * 字段 MAP */ LINKEDHASHMAP <String, String> FieldMap; Hashmap <string, string> dictypes; / ** * 构造函数 * @param Título 表格标题 , 传 传 “空值” , 表示无标题 * @param CLS 实体对象 实体对象 通过 Annotation.Exportfield 获取标题 */ public ExportExcel (título de cadena, clase <?> CLS) {this (Título, CLS, 1); } / ** * 构造函数 * @param Título 表格标题 , 传 传 “空值” , 表示无标题 * @param FieldMap , 获取要导出的字段和字段标题 * / public ExportExcel (Title de cadena, LinkedHashMap <String, String> FieldMap) {this.fieldMap = FieldMap; dictypes = new HashMap <String, String> (); // Inicializar int colunm = 0; List <String> HeaderList = lists.newarrayList (); for (tecla de cadena: fieldmap.keySet ()) {string t = fieldmap.get (key); Hashmap <string, string> map = com.thinkgem.jeesite.common.utils.stringutils.tomap (t, ";", "=", falso); if (map.get ("name")! = null) {t = map.get ("nombre"); } if (map.get ("dictype")! = null) {dictypes.put (""+(colunm), map.get ("dictype")); } colunm ++; HeaderList.Add (t); } Initialize (Title, HeaderList); } / ** * 构造函数 * @param Título 表格标题 , 传 传 “空值” , 表示无标题 * @param cls 实体对象 , 通过 通过 anotation.exportfield 获取标题 * @param type 导出类型( 1: 导出数据; 2 : * @param grupos 导入分组 * / public exportExcel (título de cadena, clase <?> Cls, int type, int ... grupos) cls.getDeclaredfields (); para (campo f: fs) {Excelfield ef = f.getAnnotation (Exfelfield.class); if (ef! = null && (ef.type () == 0 || ef.type () == type)) {if (groups! = null && groups.length> 0) {boolean ingroup = false; para (int g: grupos) {if (innoup) {break; } for (int efg: ef.groups ()) {if (g == efg) {innoup = true; annotationList.add (nuevo objeto [] {ef, f}); romper; }}}} else {annotationList.add (nuevo objeto [] {ef, f}); }}} // El método del método de anotación GET [] ms = cls.getDeclaredMethods (); para (método m: ms) {exalfield ef = m.getAnnotation (Excelfield.class); if (ef! = null && (ef.type () == 0 || ef.type () == type)) {if (groups! = null && groups.length> 0) {boolean ingroup = false; para (int g: grupos) {if (innoup) {break; } for (int efg: ef.groups ()) {if (g == efg) {innoup = true; annotationList.add (nuevo objeto [] {ef, m}); romper; }}}} else {annotationList.add (nuevo objeto [] {ef, m}); }}} // clasificación de campo Collections.sort (AnnotationList, New Comparator <Object []> () {public int Compare (Object [] o1, objeto [] o2) {return new Integer (((ExcEffield) o1 [0]). Sort ()). CompareTo (New Integer (((ExcOffield) O2 [0]).);};};};});} // Inicializar la lista <string> headerList = lists.newarrayList (); for (objeto [] OS: annotationList) {String t = ((ExcEffield) 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 Título 表格标题 , 传 传 “空值” , 表示无标题 * @param encabezados 表头数组 * / public exportExcel (título de cadena, cadena [] encabezados) {inicialize (title, lists.newarrayList (encabezados)); } / ** * 构造函数 * @param Título 表格标题 , 传 传 “空值” , 表示无标题 * @param HeaderList 表头列表 * / public exportExcel (título de cadena, List <String> HeaderList) {Initialize (title, HeaderList); } / ** * 初始化函数 * @param Título 表格标题 , 传 传 “空值” , 表示无标题 * @param HeaderList 表头列表 * / private void Initialize (Título de cadena, List <String> HeaderList) {this.wb = nuevo SXSSFWorkbook (500); this.sheet = wb.createSheet ("export"); this.styles = createstyles (wb); // Crear título if (stringUtils.isnotblank (title)) {fila titlerow = sheet.createrow (Rownum ++); Titlerow.SetHEightInpoints (30); Cell TitleCell = Titlerow.CreateCell (0); titlecell.setCellStyle (styles.get ("title")); TITLECELL.SetCellValue (título); Shead.AddMergedRegion (New CellRangeadDress (titlerow.getRownum (), titlerow.getRownum (), titlerow.getRownum (), HeaderList.Size ()-1)); } // Crear encabezado if (HeaderList == NULL) {Throw New RuntimeException ("¡HeaderList no NULL!"); } Fila headerrow = sheet.createrow (Rownum ++); Headerrow.SetHEightinPoints (16); para (int i = 0; i <headerList.size (); i ++) {celular = headerrow.createCell (i); Cell.SetCellStyle (styles.get ("encabezado")); String [] ss = stringUtils.split (HeaderList.get (i), "**", 2); if (ss.length == 2) {cell.setCellValue (ss [0]); Comentario comentario = this.sheet.createRawingpatriarch (). CreateCellComment (nuevo XSSFClientArChor (0, 0, 0, 0, (corto) 3, 3, (corto) 5, 6)); comentario Cell.SetCellComment (comentario); } else {cell.setCellValue (HeaderList.get (i)); } hoja.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 ("Inicializar el éxito"); } / ** * 创建表格样式 * @param wb 工作薄对象 * @return 样式列表 * / private map <string, cellStyle> createStyles (Workbook wb) {map <string, cellStyle> styles = new Hashmap <String, CellStyle> (); CellStyle Style = WB.CreateCellStyle (); style.setAlignment (CellStyle.Align_Center); style.setVerticalAlignment (CellStyle.vertical_center); Font titleFont = wb.createFont (); titleFont.SetFontName ("Arial"); titleFont.setFontheLightInpoints ((breve) 16); titleFont.SetBoldweight (font.boldweight_bold); style.setFont (titleFont); styles.put ("título", estilo); estilo = 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.setFontheLightInpoints ((corto) 10); style.setFont (dataFont); styles.put ("datos", estilo); estilo = wb.createCellStyle (); style.clonestyleFrom (styles.get ("data")); style.setAlignment (CellStyle.align_left); styles.put ("data1", estilo); estilo = wb.createCellStyle (); style.clonestyleFrom (styles.get ("data")); style.setAlignment (CellStyle.Align_Center); styles.put ("data2", estilo); estilo = wb.createCellStyle (); style.clonestyleFrom (styles.get ("data")); style.setAlignment (CellStyle.align_right); styles.put ("data3", estilo); estilo = 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.SetFontheLightInpoints ((corto) 10); HeaderFont.SetBoldweight (font.boldweight_bold); HeaderFont.SetColor (indexedColors.white.getIndex ()); style.setFont (HeaderFont); styles.put ("encabezado", estilo); estilos de regreso; } / ** * 添加一行 * @return 行对象 * / public fila addrow () {return hoja.createrow (Rownum ++); } / ** * 添加一个单元格 * @param fila 添加的行 * @param columna 添加列号 * @param val 添加值 * @return 单元格对象 * / public cell addcell (fila fila, int columna, objeto val) {return this.addcell (fila, columna, val, 0, class.class); } / ** * 添加一个单元格 * @param row 添加的行 * @param columna 添加列号 * @param val 添加值 * @param align 对齐方式( 1 : 靠左; 2 : 居中; 3 : 靠右) * @return 单元格对象 * / public cell addcell (fila fila, int columna, objeto val, int alinear, class <?> FieldType) {celular = row.createCell (columna); CellStyle style = styles.get ("data"+(align> = 1 && align <= 3? Align: "")); intente {if (val == null) {cell.setCellValue (""); } else if (val instanciaf string) {cell.setCellValue ((string) val); } else if (val instanciaf integer) {cell.setCellValue ((integer) val); } else if (val instancia de long) {cell.setCellValue ((long) val); } else if (val instanciaf doble) {cell.setCellValue (new DecimalFormat (". #####"). Format (val)); } else if (val instanciaf float) {cell.setCellValue ((float) val); } else if (val instanciaf fecha) {dataFormat format = wb.createedataformat (); 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 (). GetSimpLename (), "fieldType."+val.getClass (). getSimplenPlenNeMe }}} capt (excepción ex) {log.info ("establecer el valor de la celda ["+row.getRownum ()+","+columna+"] error:"+ex.ToString ()); Cell.SetCellValue (val.ToString ()); } cell.setCellStyle (estilo); celda de retorno; } / ** * 添加数据(通过 Annotation.Exportfield 添加数据) * @@return list 数据列表 * / public <e> exportExcel setDatalist (list <E> list) {for (e e: list) {int colunm = 0; Fila fila = this.addrow (); StringBuilder sb = new StringBuilder (); if (e instanceof map) {@suppleswarnings ("sin verificar") map <string, object> map = (map <string, object>) e; for (tecla de cadena: fieldmap.KeySet ()) {objeto valor = map.get (key); String columndicttype = dictypes.get (colunm+""); if (stringUtils.isnotblank (columnDicttype)) {value = dictUtils.getDictLabel (value == null? "": value.ToString (), columnDictType, ""); } this.addcell (fila, colunm ++, value == null? "": value.ToString (), 0, string.class); sb.append (valor + ","); }} else {for (object [] OS: annotationList) {ExcEffield ef = (Excelfield) OS [0]; Objeto val = nulo; // Obtener valor de entidad Try {if (StringUtils.isNotBlank (ef.value ())) {val = refless.invokeGetter (e, ef.value ()); } else {if (OS [1] instanceof campo) {val = refless.invokegetter (e, ((campo) os [1]). getName ()); } else if (OS [1] instancia de método) {val = reflexss.invokemethod (e, ((método) os [1]). getName (), nueva clase [] {}, nuevo objeto [] {}); }} // if es dict, obtenga la etiqueta dict if (stringUtils.isnotblank (ef.dicttype ())) {val = dictUtils.getDictLabel (val == null? "": Val.ToString (), ef.dicttype (), "); }} Catch (Exception Ex) {// No ignorar log.info (ex.ToString ()); val = ""; } this.addcell (fila, colunm ++, val, ef.align (), ef.fieldtype ()); sb.append (val + ","); } log.debug ("Escribir éxito: ["+Row.getRownum ()+"]"+SB.ToString ()); }} devuelve esto; } / ** * 输出数据流 * @param OS 输出数据流 * / public ExportExcel Write (OutputStream OS) lanza ioexception {wb.write (os); devolver esto; } / ** * 输出到客户端 * @param nombre de archivo 输出文件名 * / public exportExcel write (httpServletResponse Respuesta, String FileName) lanza IOException {Response.reset (); respuesta.setContentType ("Application/Octet-Stream; Charset = UTF-8"); Respuesta.Setheader ("Disposición de contenido", "Adjunto; FileName ="+Encodes.Urlencode (FileName)); escribir (respuesta.getOutputStream ()); devolver esto; } / ** * 输出到文件 * @param nombre de archivo 输出文件名 * / public exportExcel writeFile (name de cadena) lanza FileNotFoundException, ioException {FileOutputStream OS = new FileOutputStream (name); this.write (OS); devolver esto; } / ** * 清理临时文件 * / public ExportExcel Dispose () {wb.dispose (); devolver esto; }}导出测试
public static void main (string [] args) lanza lanzable {list <string> headerList = lists.newarrayList (); para (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 ++) {fila fila = ee.addrow (); for (int j = 0; j <dataList.get (i) .size (); j ++) {ee.addcell (fila, j, dataList.get (i) .get (j)); }} ee.writeFile ("Target/export.xlsx"); ee.dispose (); log.debug ("Exportar éxito"); }Importexcel.java
/*** Copyright © 2012-2014 <a href = "https://github.com/thinkgem/jeesite"> jeesite </a> Todos los derechos reservados. */paquete 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; importar org.apache.commons.lang3.StringUtils; import org.apache.poi.hssf.usermodel.hssfworkbook; import org.apache.poi.openxml4j.exceptions.invalidformatexception; import org.apache.poi.s.usermodel.cell; import org.apache.poi.ss.usermodel.dateutil; import org.apache.poi.ss.usermodel.row; importar org.apache.poi.ss.usermodel.sheet; importar org.apache.poi.ss.usermodel.workBook; import org.apache.poi.xssf.usermodelsmfworkbook; org.slf4j.logger; import org.slf4j.loggerFactory; import org.springframework.web.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.util.dictutils; /** * 导入 Excel 文件(支持 “XLS” 和 “XLSX” 格式) * @Author ThinkGem * @Version 2013-03-10 */public class ImportExcel {private static logGer = loggerFactory.getLogger (importexcel.class); / ** * 工作薄对象 */ Libro de trabajo privado WB; / ** * 工作表对象 */ Hoja privada; / ** * 标题行号 */ private int headernum; / ** * 构造函数 * @param ruta 导入文件 , 读取第一个工作表 * @param headernum 标题行号 , 数据行号 = 标题行号 +1 * @throws InvalidFormateException * @throws ioexception */ public importexcel (string fileName, int headernum) lanza InvalidFormAcception, ioException {este (nuevo archivo FileName), Headernum); } / ** * 构造函数 * @param ruta 导入文件对象 , 读取第一个工作表 * @param headernum 标题行号 , 数据行号 = 标题行号 +1 * @throws invalidFormateException * @throws ioexception * / public importexcel (archivo archivo, int headernum) lanza InvalidFormAxception, ioexception {this (archivo, headernum, 0); } /** * 构造函数 * @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 ruta 导入文件对象 * @param headernum 标题行号 , 数据行号 = 标题行号 +1 * @param sheetindex 工作表编号 * @throws invalidFormateException * @throws ioException * / public importexcel (archivo archivo, int headernum, int sheEndEx) tira invalidFormatexception, iOException {this (file.getName (name (), (), (), intraineax) tira InvalidAxception, iOException {this (file.getName ((), (), (), INT SKEINDEX) tira InvalIdFormCeption, ioException {this (file.getName ((), (), (), (), (), lanza InvalidException, iOException {this (archivo. Headernum, SheetIndex); } / ** * 构造函数 * @param archivo 导入文件对象 * @param headernum 标题行号 , 数据行号 = 标题行号 +1 * @param sheetindex 工作表编号 * @throws invalidFormateException * @throws ioException * / public importexcel (multipartfile multipartFile, int headernum, int shitex) tira invalidformatexception, ioexception { this (multipartFile.getOriginalFileName (), multipartfile.getInputStream (), headernum, sheetIndex); } / ** * 构造函数 * @param ruta 导入文件对象 * @param headernum 标题行号 , 数据行号 = 标题行号 +1 * @param sheetindex 工作表编号 * @throws invalidFormateException * @throws ioException * / public importexcel (String fileNeame, inputStream IS, int headernum, int shitex) lanza invalidformatexception, IoException {if ibeame {si (StringUtils.isblank (nombre de archivo)) {tire 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 {lanzar nueva runtimeException ("文档格式不正确!"); } if (this.wb.getNumberOfSheets () <sheetIndex) {Throw New RuntimeException ("文档中没有工作表!"); } this.sheet = this.wb.getSheetat (sheetIndex); this.headernum = headernum; log.debug ("Inicializar el éxito"); } / ** * 获取行对象 * @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 fila 获取的行 * @param columna 获取单元格列号 * @return 单元格值 * / public objeto getCellValue (fila fila, int columna) {objeto val = ""; intente {celular = row.getCell (columna); 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 (); }}} capt (excepción e) {return val; } return val; } / ** * 获取导入数据列表 * @param Cls 导入对象类型 * @param grupos 导入分组 * / public <e> list <E> getDatalist (class <E> cls, int ... grupos) lanza InstanciationException, ilegalAccessException {list <Object []> annotationList = lists.newarrayList (); // Campo de campo de anotación [] fs = cls.getDeclaredfields (); para (campo f: fs) {Excelfield ef = f.getAnnotation (Exfelfield.class); if (ef! = null && (ef.type () == 0 || ef.type () == 2)) {if (groups! = null && groups.length> 0) {boolean ingroup = false; para (int g: grupos) {if (innoup) {break; } for (int efg: ef.groups ()) {if (g == efg) {innoup = true; annotationList.add (nuevo objeto [] {ef, f}); romper; }}}} else {annotationList.add (nuevo objeto [] {ef, f}); }}} // El método del método de anotación GET [] ms = cls.getDeclaredMethods (); para (método m: ms) {exalfield ef = m.getAnnotation (Excelfield.class); if (ef! = null && (ef.type () == 0 || ef.type () == 2)) {if (groups! = null && groups.length> 0) {boolean ingroup = false; para (int g: grupos) {if (innoup) {break; } for (int efg: ef.groups ()) {if (g == efg) {innoup = true; annotationList.add (nuevo objeto [] {ef, m}); romper; }}}} else {annotationList.add (nuevo objeto [] {ef, m}); }}} // clasificación de campo Collections.sort (AnnotationList, New Comparator <Object []> () {public int Compare (Object [] o1, objeto [] o2) {return new Integer (((ExcEffield) o1 [0]). Sort ()). CompareTo (New Integer (((ExcOffield) O2 [0]).);};};};});} //log.debug("Import Column Count: "+annotationList.size ()); // Obtener lista de datos de Excel <E> dataList = lists.newarrayList (); para (int i = this.getDatarOwnum (); i <this.getLastDatarOwnum (); i ++) {e e = (e) cls.newinstance (); int columna = 0; Fila fila = this.getrow (i); StringBuilder sb = new StringBuilder (); for (objeto [] OS: annotationList) {objeto val = this.getCellValue (fila, columna ++); if (val! = null) {exalfield ef = (exalfield) os [0]; // si es tipo dict, obtenga el valor de dict if (stringUtils.isnotblank (ef.dicttype ())) {val = dictUtils.getDictValue (val.ToString (), ef.dicttype (), ""); //log.debug("Diccionario Valor de tipo: ["+i+", "+colunm+"] "+val); } // Obtener tipo de parámetro y tipo de clase Cast <?> Valtype = class.class; if (os [1] instanciaf campo) {valtype = ((campo) os [1]). getType (); } else if (OS [1] instanciaf método) {método método = ((método) os [1]); if ("get" .equals (método.getName (). sustring (0, 3))) {valtype = método.getReturnType (); } else if ("set" .equals (método.getName (). sustring (0, 3))) {valtype = ((método) os [1]). getparametertypes () [0]; }} //log.debug("Import Tipo de valor: ["+i+", "+columna+"] "+Valtype); intente {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 ((doble) 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 (Exception Ex) {Log.info ("Get Cell Value ["+I+","+Column+"] Error:"+ex.ToString ()); val = nulo; } // Establecer el valor de la entidad if (OS [1] instanceof campo) {reflexions.invokesetter (e, ((campo) os [1]). getName (), val); } else if (OS [1] instancia de método) {string mtHodName = ((método) os [1]). getName (); if ("get" .equals (mtHodName.substring (0, 3))) {mtHodName = "set"+stringUtils.substringafter (mThodName, "get"); } Reflexss.invokemethod (e, mtHodName, nueva clase [] {Valtype}, nuevo objeto [] {val}); }} sb.append (val+","); } dataList.Add (e); log.debug ("Leer el éxito: ["+i+"]"+sb.toString ()); } return dataList; }}导入测试
public static void main (string [] args) lanza lando {importexcel ei = new importexcel ("target/export.xlsx", 1); for (int i = ei.getDatarOwnum (); i <ei.getLastDatarOwnum (); i ++) {fila fila = ei.getrow (i); for (int j = 0; j <ei.getLastCellNum (); j ++) {objeto val = ei.getCellValue (fila, j); System.out.print (val+","); } System.out.print ("/n"); }}