文件导入导出必须代码
ExportExcel.java
/*** Copyright © 2012-2014 <a href = "https://github.com/thinkgem/jeesite"> jeesite </a> Все права защищены. */package com.thinkgem.jeesite.common.utils.excel; Импорт java.io.filenotFoundException; Import java.io.fileOutputStream; импорт java.io.ioexception; импорт java.io.outputstream; импорт java.lang.reflect.field; import java.lang.reflect.method; импорт java.text.decimalformat; импорт. java.util.comparator; import java.util.date; import java.util.hashmap; импорт java.util.linkedhashmap; import java.util.list; import java.util.map; Импорт javax.servlet.http.httpservletresponse; Импорт 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; импорт org.apache.poi.ss.susermodel. 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.pache.poi.s.shoodel. org.apache.poi.ss.util.cellrangeaddress; import org.apache.poi.xssf.streaming.sxssfworkbook; import org.apache.poi.xssf.usermodel.xsfclientanchor; импорт org.apache.poi.xssf.usssring. org.slf4j.logger; импорт org.slf4j.loggerfactory; Импорт com.google.common.collect.lists; import com.thinkgem.jeesite.common.utils.dateutils; import com.theinkgem.jeesite.common.utils.encodes; импорт com.thinkgem.jeesite.common.utils.reflections; импорт com.thinkgem.jeesite.common. com.thinkgem.jeesite.modules.sys.utils.dictutils; /** * 导出 Excel 文件 (导出 «xlsx» 格式 , 支持大数据量导出 @see org.apache.poi.ss.spreadsheetversion) * @author thinkgem * @version 2013-04-21 */public exportexcel {private static log = loggerfactory.getgger (exprort.class / ** * 工作薄对象 */ private sxssfworkbook wb; / ** * 工作表对象 */ Частный лист; / ** * 样式列表 */ Private Map <String, cellStyle> styles; / ** * 当前行号 */ private int rownum; /** * 注解列表 (Object [] {Excelfield, Field/Method}) */List <Object []> AnnotationList = lists.newarrayList (); / ** * 字段 Map */ linkedHashmap <string, string> fieldmap; HashMap <String, String> dictTypes; / ** * 构造函数 * @param title 表格标题 , 传 «空值» , 表示无标题 * @param cls 实体对象 通过 通过 annotation.exportfield 获取标题 */ public exportexcel (название строки, класс <?> Cls) {this (title, cls, 1); } / ** * 构造函数 * @param title 表格标题 , 传 «空值» , 表示无标题 * @param fieldmap , 获取要导出的字段和字段标题 * / public exportexcel (название строки, 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); } инициализировать (заголовок, заголовок); } / ** * 构造函数 * @param title 表格标题 , 传 传 空值 空值 , 表示无标题 * @param cls 实体对象 , 通过 annotation.exportfield 获取标题 * @param type 导出类型 (1: 导出数据; 2 : :)) cls.getdeclaredfields (); для (поле F: Fs) {Excelfield ef = f.getannotation (Excelfield.class); if (ef! = null && (ef.type () == 0 || ef.type () == type)) {if (группы! = null && groups.length> 0) {boolean Ingroup = false; for (int g: группы) {if (Ingroup) {break; } for (int efg: ef.groups ()) {if (g == efg) {Ingroup = true; annotationlist.add (новый объект [] {ef, f}); перерыв; }}}} else {annotationlist.add (new Object [] {ef, f}); }}} // Получить метод метода аннотации [] ms = cls.getDeclaredMethods (); for (метод M: MS) {Excelfield ef = m.getannotation (Excelfield.class); if (ef! = null && (ef.type () == 0 || ef.type () == type)) {if (группы! = null && groups.length> 0) {boolean Ingroup = false; for (int g: группы) {if (Ingroup) {break; } for (int efg: ef.groups ()) {if (g == efg) {Ingroup = true; annotationlist.add (новый объект [] {ef, m}); перерыв; }}}} else {annotationlist.add (новый объект [] {ef, m}); }}} // Сортация поля Сборник. SORT (AnnotationList, новый компаратор <Object []> () {public int compare (Object [] O1, Object [] o2) {return new Integer (((Excelfield) O1 [0]). Sort ()). CompareTo (New Integer (((Excelfield) O2 [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); } инициализировать (заголовок, заголовок); } / ** * 构造函数 * @param title 表格标题 , 传 «空值» , 表示无标题 * @param заголовки 表头数组 * / public exportexcel (название строки, строка [] заголовки) {initiaze (title, lists.newarraylist (headers)); } / ** * 构造函数 * @param title 表格标题 , 传 «空值» , 表示无标题 * @param headerlist 表头列表 * / public exportexcel (название строки, список <string> headerlist) {initiaze (title, headerlist); } / ** * 初始化函数 * @param title 表格标题 , 传 «空值» , 表示无标题 * @param headerlist 表头列表 * / private void инициализация (название строки, список <string> headerlist) {this.wb = new sxssfworkbook (500); this.sheet = wb.createsheet ("Экспорт"); this.styles = createstyles (wb); // Создать заголовок if (stringUtils.isnotblank (title)) {row titlerow = sheet.createrow (rownum ++); titlerow.setheightinpoints (30); Ячейка titlecell = titlerow.createCell (0); titlecell.setcellstyle (styles.get ("title")); titlecell.setcellvalue (заголовок); sheet.addmergedregion (new cellrangaddress (titlerow.getrownum (), titlerow.getrownum (), titlerow.getrownum (), headerlist.size ()-1)); } // Создать заголовок if (headerlist == null) {бросить новый runtimeexception ("headerlist не 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 (новый xssfclientanchor (0, 0, 0, 0, (короткий) 3, 3, (короткий) 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 (рабочая книга wb) {map <string, cellstyle> styles = new Hashmap <String, cellStyle> (); CellStyle Style = wb.createCellStyle (); Style.SetAlignment (cellStyle.align_center); style.seterticalAlignment (cellstyle.vertical_center); Font titlefont = wb.createfont (); titleFont.SetFontName ("Arial"); TitleFont.SetFonTheItinPoints ((короткий) 16); titleFont.SetBoldWeight (font.Boldweight_bold); style.setfont (titlefont); styles.put ("название", стиль); style = wb.createcellstyle (); style.seterticalAlignment (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.SetFonTheItinPoints ((короткий) 10); style.setfont (datafont); styles.put ("data", style); style = wb.createcellstyle (); style.clonestylefrom (styles.get ("data")); style.setalenment (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.setfontheithinpoints ((короткий) 10); headerfont.setboldweight (font.boldewele_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 (row, crow, столбец, объект val) {return this.addcell (row, clorb, val, 0, class.class); } / ** * 添加一个单元格 * @param row 添加的行 * @param столбец 添加列号 * @param val 添加值 * @param align 对齐方式 (1 : 靠左; 2 : 居中; 3 : 靠右) * @return 单元格对象 * / public cell Addcell (строка строки, int column val, int align, class <?> Fieldtype) {cell Cell = row.crell (COLMAN CellStyle style = styles.get ("data"+(align> = 1 && align <= 3? Align: "")); попробуйте {if (val == null) {cell.setcellvalue (""); } else if (val ancess string) {cell.setcellvalue (((string) val); } else if (val ancessionof integer) {cell.setcellvalue (((Integer) val); } else if (val ancessionof long) {cell.setcellvalue ((long) val); } else if (val ancessionof double) {cell.setcellvalue (new decimalformat (". #####"). format (val)); } else if (val ancessionof float) {cell.setcellvalue (((float) val); } else if (val ancessionof 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 (). ryplaceAll (this.getClass (). getSiMplename (), "fieldType."+val.getClass (). getSiMplename ()+"type"). getMethod ("setvalue", object. }}} catch (Exception ex) {log.info ("Установить значение ячейки ["+row.getRownum ()+","+column+"] ошибка:"+ex.toString ()); cell.SetCellValue (val.ToString ()); } cell.setCellStyle (стиль); возвращаемая ячейка; } / ** * 添加数据 (通过 annotation.exportfield 添加数据) * @return List 数据列表 * / public <e> exportexcel setDatalist (list <e> list) {for (e e: list) {int colunm = 0; Row row = this.addrow (); StringBuilder SB = new StringBuilder (); if (e EncanceOf map) {@suppresswarnings ("unchecked") map <string, object> map = (map <string, object>) e; for (String Key: fieldmap.keyset ()) {object value = map.get (key); String 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 (значение + ","); }} else {for (Object [] OS: AnnotationList) {Excelfield ef = (Excelfield) OS [0]; Объект val = null; // Получить значение объекта try {if (stringUtils.isnotblank (ef.value ())) {val = Reflections.invokegetter (e, ef.value ()); } else {if (os [1] exanteof field) {val = Reflections.invokegetter (e, ((Field) OS [1]). getName ()); } else if (os [1] exanceof method) {val = Reflections.invokemethod (e, ((метод) OS [1]). getName (), новый класс [] {}, новый объект [] {}); }} // Если дикта, получите метку DICT 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 输出数据流 * / public exportexcel write (outputstream os) бросает ioexception {wb.write (os); вернуть это; } / ** * 输出到客户端 * @param filename 输出文件名 * / public exportexcel write (httpservletresponse response, string filename) бросает ioexception {response.reset (); response.setContentType ("Приложение/Octet-Stream; charset = utf-8"); response.setheader ("Содержимое-распада", "Приложение; filename ="+eNcodes.urlencode (имя файла)); write (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) бросает throwable {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 ++) {datarowist.add ("数据"+i); } List <list <string >> datalist = lists.newarraylist (); for (int i = 1; i <= 1000000; i ++) {datalist.add (dataRowist); } 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
/*** Copyright © 2012-2014 <a href = "https://github.com/thinkgem/jeesite"> jeesite </a> Все права защищены. */package com.thinkgem.jeesite.common.utils.excel; Импорт java.io.file; импорт java.io.fileinputstream; import java.io.ioexception; импорт java.io.inputstream; импорт java.lang.reflect.field; импорт java.lang.reflect.method; импорт java.util.collections; импорт Java.ut.comparator; java.util.list; Импорт org.apache.commons.lang3.stringutils; import org.apache.poi.hssf.usermodel.hssfworkbook; import org.apache.poi.openxml4j.exceptions.invalidformatexception; импорт org.apache.poi.ss.esel.cell; 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.pohe.poi.ssssf.xslipbook org.slf4j.logger; импорт org.slf4j.loggerfactory; import org.springframework.web.multipart.multipartfile; Импорт com.google.common.collect.lists; import com.thinkgem.jeesite.common.utils.reflections; импорт com.thinkgem.jeesite.common.utils.excel.annotation.excelfield; импорт com.thinkgem.jeesite.modules.sylation.dictutils; /** * 导入 Excel 文件 (支持 «xls» 和 «xlsx» 格式) * @author thinkgem * @version 2013-03-10 */public class importexcel {private static logger = loggerfactory.getlogger (impormexcel.class); / ** * 工作薄对象 */ частная рабочая тетрадь WB; / ** * 工作表对象 */ Частный лист; / ** * 标题行号 */ private int headernum; / ** * 构造函数 * @param path 导入文件 , 读取第一个工作表 * @param Headernum 标题行号 , 数据行号 = 标题行号 +1 * @Throws InvalidFormateXception * @Throws ioException */ public importExcel (string fileenum, int headernum) бросает Invalidformatexception, ioException {this (new File (filename), Headernum); } / ** * 构造函数 * @param path 导入文件对象 , 读取第一个工作表 * @param headernum 标题行号 , 数据行号 = 标题行号 +1 * @throhs Invalidformatexception * @Throws IOException * / public ImportExcel (файл файла, int headernum) бросает InvalidFormatexception, ioException {this (файл, 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 path 导入文件对象 * @param headernum 标题行号 , 数据行号 = 标题行号 +1 * @param sheetIndex 工作表编号 * @Throws InvalidFormateXception * @Throws ioException * / public importExcel (файл, int headernum, int sheateIndex) throwsemememememememememememememem Headernum, SheetIndex); } / ** * 构造函数 * @param file 导入文件对象 * @param headernum 标题行号 , 数据行号 = 标题行号 +1 * @param sheateindex 工作表编号 * @throws Invalidformatexception * @Throws IOException * / public ImportExcel (MultipartFile MultipartFile, int Headerum, int sheetIndex) throws validformatexcept это (multiplaartfile.getoriginalfilename (), multiplaartfile.getInputStream (), Headernum, SheetIndex); } / ** * 构造函数 * @param path 导入文件对象 * @param headernum 标题行号 , 数据行号 = 标题行号 +1 * @param sheetIndex 工作表编号 * @Throws InvalidFormateXception * @Throws ioException * / public ImportExcel (String filename, inputStream, int headernum, int sheateDex) trows invalidformatexcection, ioExcept (StringUtils.isblank (имя файла)) {бросить новое 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 () <sheateindex) {бросить новое 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 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 (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 (Exception e) {return val; } return val; } / ** * 获取导入数据列表 * @param cls 导入对象类型 * @param Groups 导入分组 * / public <e> list <e> getDatalist (class <e> cls, int ... группы) бросает InstantiationException, allodalAccessexception {list <Object []> AnnotationList = lists.newarrayList (); // Получить поле аннотации поля [] fs = cls.getDeclaredFields (); для (поле F: Fs) {Excelfield ef = f.getannotation (Excelfield.class); if (ef! = null && (ef.type () == 0 || ef.type () == 2)) {if (группы! = null && groups.length> 0) {boolean Ingroup = false; for (int g: группы) {if (Ingroup) {break; } for (int efg: ef.groups ()) {if (g == efg) {Ingroup = true; annotationlist.add (новый объект [] {ef, f}); перерыв; }}}} else {annotationlist.add (new Object [] {ef, f}); }}} // Получить метод метода аннотации [] ms = cls.getDeclaredMethods (); for (метод M: MS) {Excelfield ef = m.getannotation (Excelfield.class); if (ef! = null && (ef.type () == 0 || ef.type () == 2)) {if (группы! = null && groups.length> 0) {boolean Ingroup = false; for (int g: группы) {if (Ingroup) {break; } for (int efg: ef.groups ()) {if (g == efg) {Ingroup = true; annotationlist.add (новый объект [] {ef, m}); перерыв; }}}} else {annotationlist.add (новый объект [] {ef, m}); }}} // Сортация поля Сборник. SORT (AnnotationList, новый компаратор <Object []> () {public int compare (Object [] O1, Object [] o2) {return new Integer (((Excelfield) O1 [0]). Sort ()). CompareTo (New Integer (((Excelfield) O2 [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 column = 0; Row 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 if (stringUtils.isnotblank (ef.dicttype ())) {val = dictutils.getdictvalue (val.toString (), ef.dicttype (), ""); //log.debug("dictionary тип значения: ["+i+", "+colunm+"] "+val); } // Получить тип параметра и тип класса CAST <?> Valtype = class.class; if (os [1] exanteof field) {valtype = ((Field) OS [1]). getType (); } else if (os [1] exanceof method) {method method = ((method) os [1]); if ("get" .equals (method.getName (). substring (0, 3))) {valType = method.getReturnType (); } else if ("set" .equals (method.getName (). substring (0, 3))) {valType = ((метод) 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 (). ReplaceAll (this.getClass (). getSiMplename (), "fieldType."+valtype.getSimplename ()+"type")). getMethod ("getValue", String.Class) .invoke (null, val }}} catch (Exception ex) {log.info ("получить значение ячейки ["+i+","+column+"] error:"+ex.toString ()); val = null; } // Установить значение объекта if (os [1] exanceOf field) {Reflections.invokesetter (e, ((Field) OS [1]). getName (), val); } else if (os [1] exanceof method) {string mthodName = ((метод) OS [1]). getName (); if ("get" .equals (mthodname.substring (0, 3))) {mthodname = "set"+stringutils.substringafter (mthodname, "get"); } Reflections.invokemethod (e, mthodname, новый класс [] {valtype}, new Object [] {val}); }} sb.append (val+","); } datalist.add (e); log.debug ("Читать успех: ["+i+"]"+sb.tostring ()); } вернуть Datalist; }}导入测试
public static void main (string [] args) бросает Throwable {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"); }}