文件导入导出必须代码
Exportexcel.java
/*** Hak Cipta © 2012-2014 <a href = "https://github.com/thinkgem/jeesite"> jeesite </a> Semua hak dilindungi undang-undang. */paket com.thinkgem.jeesite.common.utils.excel; impor java.io.filenotfoundException; impor java.io.fileoutputstream; impor java.io.ioException; impor java.io.outputstream; java.util.comparator; import java.util.date; import java.util.hashmap; import java.util.linkedhashmap; import java.util.list; import java.util.map; impor javax.servlet.http.httpservletResponse; Impor org.apache.commons.lang3.stringutils; impor org.apache.poi.ss.usermodel.cell; impor org.apache.poi.ss.usermodel.cellstyle; import org.apache.poi.usermodel.coModel.dort; import org.apache.poi 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 org.apache.poi.ss.util.cellrangeaddress; impor org.apache.poi.xssf.streaming.sxssfworkbook; import org.apache.poi.xssf.usermodel.xsfclientanchor; import org.apache.poi.xsssflixhanchor; org.slf4j.logger; impor org.slf4j.loggerFactory; impor com.google.common.collect.lists; import com.thinkgem.jeesite.common.utils.dateutils; import com.thinkgem.jeesite.common.utils.encodes; impor com.thinkgem.jeesite.common.utils.reflections; Impor; com.thinkgem.jeesite.common.utils.excel.annotation.excelfield; impor com.thinkgem.jeesite.modules.sys.utils.dictutils; /** * 导出 excel 文件(导出 “xlsx” 格式 , 支持大数据量导出 @see org.apache.poi.ss.spreadsheetVersion) * @Author thinkgem * @Version 2013-04-21 */Public Class ExportExcel {private static logger log = loggerefactory.getlogger.Epport. Export {private static logg LOG = loggerFacTory.getlogger.Epport. / ** * 工作薄对象 */ private sxssfworkbook wb; / ** * 工作表对象 */ lembar privat; / ** * 样式列表 */ peta pribadi <string, cellstyle> styles; / ** * 当前行号 */ private int rownum; /** * 注解列表( objek [] {excelfield, field/method}) */list <object []> annotationlist = lists.newarraylist (); / ** * 字段 peta */ linkedHashMap <string, string> fieldmap; HashMap <String, String> DictTypes; / ** * 构造函数 * @param title 表格标题 , 传 “空值” , 表示无标题 * @param cls 实体对象 , 通过 annotation.Exportfield 获取标题 */ public exportexcel (judul string, kelas <?> Cls) {this (title, cls, 1); } / ** * 构造函数 * @param title 表格标题 , 传 “空值” , 表示无标题 * @param fieldmap , 获取要导出的字段和字段标题 * / public exportexcel (string title, linkedHashMap <string, string> fieldmap) {this.fieldmap = fieldmap; dicttypes = hashmap baru <string, string> (); // inisialisasi int colunm = 0; Daftar <String> headerList = lists.newArrayList (); untuk (tombol string: fieldmap.keyset ()) {string t = fieldmap.get (key); Hashmap <string, string> peta = 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 (judul, headerlist); } / ** * 构造函数 * @param title 表格标题 , 传 “空值” , 表示无标题 * @param cls 实体对象 , 通过 annotation.Exportfield 获取标题 * @param Tipe 导出类型( 1: 导出数据; 2 : 导出模板) * @param 导入分组 * / public exportexcel (string title, class <?> Cls, tipe int ... cls.getDeclaredFields (); untuk (bidang f: fs) {excelfield ef = f.getannotation (excelfield.class); if (ef! = null && (ef.type () == 0 || ef.type () == type)) {if (grup! = null && groups.length> 0) {boolean ingroup = false; untuk (int g: grup) {if (ingroup) {break; } untuk (int efg: ef.groups ()) {if (g == efg) {ingroup = true; annotationlist.add (objek baru [] {ef, f}); merusak; }}}} else {annotationlist.add (objek baru [] {ef, f}); }}} // Dapatkan metode anotasi metode [] ms = cls.getDeclaredMethods (); untuk (metode m: ms) {excelfield eF = m.getannotation (excelfield.class); if (ef! = null && (ef.type () == 0 || ef.type () == type)) {if (grup! = null && groups.length> 0) {boolean ingroup = false; untuk (int g: grup) {if (ingroup) {break; } untuk (int efg: ef.groups ()) {if (g == efg) {ingroup = true; annotationlist.add (objek baru [] {ef, m}); merusak; }}}} else {annotationlist.add (objek baru [] {ef, m}); }}} // Field Sorting Collections.sort (AnnotationList, Comparator Baru <Object []> () {Public int Compare (Object [] O1, Object [] o2) {return new integer (((excelfield) o1 [0]). Sort ()). Compareto (integer baru ((excelfield) o2 [) (0]). O compareto ((Excelfield); // inisialisasi daftar <string> headerList = lists.newarraylist (); untuk (objek [] 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 (judul, headerlist); } / ** * 构造函数 * @param title 表格标题 , 传 “空值” , 表示无标题 * @param header 表头数组 * / public exportexcel (string title, string [] header) {initialize (title, lists.newarraylist (headers)); } / ** * 构造函数 * @param title 表格标题 , 传 “空值” , 表示无标题 * @param HeaderList 表头列表 * / Public ExportExcel (Judul String, Daftar <String> HeaderList) {initialize (title, headerlist); } / ** * 初始化函数 * @param title 表格标题 , 传 “空值” , 表示无标题 * @param headerlist 表头列表 * / private void initialize (judul string, daftar <string> headerlist) {this.wb = SXSSFWorkBook baru (500); this.sheet = wb.createSheet ("Ekspor"); this.styles = createestyles (WB); // Buat judul if (stringutils.isnotblank (judul)) {baris titlerow = sheet.createrow (rownum ++); titlerow.setheightInpoints (30); Sel titlecell = titlerow.createCell (0); titlecell.setcellstyle (styles.get ("title")); titlecell.setCellValue (judul); sheet.addmergedregion (cellangeaddress baru (titlerow.getrownum (), titlerow.getrownum (), titlerow.getrownum (), headerlist.size ()-1)); } // Buat header if (headerList == null) {lempar runimeException baru ("headerlist not null!"); } Row headerrow = sheet.createrow (rownum ++); headerrow.setheightInpoints (16); untuk (int i = 0; i <headerlist.size (); i ++) {sel sel = headerrow.createCell (i); cell.setCellstyle (styles.get ("header")); String [] ss = stringutils.split (headerlist.get (i), "**", 2); if (ss.length == 2) {cell.setCellValue (ss [0]); Komentar komentar = this.sheet.createdrawingpatriarch (). CreateCellComment (XSSFClientanchor baru (0, 0, 0, 0, (pendek) 3, 3, (pendek) 5, 6)); Comment.setstring (XSSFrichTextString baru (SS [1])); cell.setCellComment (komentar); } else {cell.setCellValue (headerlist.get (i)); } sheet.autosizeColumn (i); } untuk (int i = 0; i <headerlist.size (); i ++) {int colwidth = sheet.getColumnWidth (i)*2; sheet.setColumnWidth (i, colwidth <3000? 3000: colwidth); } log.debug ("Inisialisasi kesuksesan."); } / ** * 创建表格样式 * @param wb 工作薄对象 * @return 样式列表 * / peta privat <string, cellstyle> createestyles (workbook wb) {peta <string, cellstyle> styles = hashmap baru <string, cellstyle> (); CellStyle Style = WB.CreateCellStyle (); style.setalignment (cellstyle.align_center); style.setVerticalAlignment (cellstyle.vertical_center); Font titlefont = wb.createFont (); titlefont.setFontName ("Arial"); titlefont.setFontheightInpoints ((pendek) 16); titlefont.setBoldWeight (font.boldweight_bold); style.setfont (titlefont); styles.put ("judul", gaya); 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 ((pendek) 10); style.setFont (datafont); styles.put ("data", gaya); style = wb.createCellstyle (); style.clonestyleFrom (styles.get ("data")); style.setalignment (cellstyle.align_left); styles.put ("data1", gaya); style = wb.createCellstyle (); style.clonestyleFrom (styles.get ("data")); style.setalignment (cellstyle.align_center); styles.put ("data2", gaya); 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 ((pendek) 10); headerfont.setBoldWeight (font.boldweight_bold); headerfont.setColor (indexedColors.white.getIndex ()); style.setfont (headerfont); styles.put ("header", style); gaya pengembalian; } / ** * 添加一行 * @return 行对象 * / public row addRow () {return sheet.createrow (rownum ++); } / ** * 添加一个单元格 * @param baris 添加的行 * @param kolom 添加列号 * @param val 添加值 * @return 单元格对象 * / sel public addcell (baris baris, kolom int, val objek) {return this.addcell (baris, kolom, val, 0, class.class); } / ** * 添加一个单元格 * @param Row 添加的行 * @param kolom 添加列号 * @param val 添加值 * @param align 对齐方式( 1 : 靠左; 2 : 居中; 3 : 靠右) * @return 单元格对象 * / sel addcell sel publik (baris baris, kolom objek, int align, kelas <?> FieldType) {sel sel = row col. Cellstyle style = styles.get ("data"+(align> = 1 && align <= 3? Align: "")); coba {if (val == null) {cell.setCellValue (""); } else if (val instance dari string) {cell.setCellValue ((string) val); } lain jika (val instance dari integer) {cell.setCellValue ((integer) val); } else if (val instance dari long) {cell.setCellValue ((long) val); } else if (val instance dari double) {cell.setCellValue (new decimalformat (". #####"). Format (val)); } else if (val instance dari float) {cell.setCellValue ((float) val); } else if (val instance dari tanggal) {format dataFormat = wb.createdataformat (); style.setDataFormat (format.getFormat ("yyyy-mm-dd")); cell.setCellValue (dateutils.FormatDateTime ((tanggal) 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 (). GetSimpleName ()+"type")). }}} catch (exception ex) {log.info ("Setel nilai sel ["+row.getRownum ()+","+kolom+"] kesalahan:"+ex.toString ()); cell.setCellValue (val.tostring ()); } cell.setCellstyle (style); sel kembali; } / ** * 添加数据(通过 annotation.Exportfield 添加数据) * @Return List 数据列表 * / public <e> ExportExcel setDataList (Daftar <E> Daftar) {untuk (e e: Daftar) {int colunm = 0; Baris baris = this.addrow (); StringBuilder SB = StringBuilder baru (); if (e instance dari peta) {@suppressWarnings ("Uncecked") peta <String, Object> peta = (peta <String, Object>) e; untuk (tombol string: fieldmap.keyset ()) {objek nilai = map.get (key); String columnDictType = dicttypes.get (colunm+""); if (stringutils.isnotblank (columnDictType)) {value = dictutils.getdictLabel (value == null? "": value.toString (), columnDictType, ""); } this.addcell (baris, colunm ++, value == null? "": value.toString (), 0, string.class); SB.Append (nilai + ","); }} else {for (objek [] os: annotationlist) {excelfield ef = (excelfield) os [0]; Objek val = null; // Dapatkan nilai entitas coba {if (stringutils.isnotblank (ef.value ())) {val = reflections.invokeGetter (e, ef.value ()); } else {if (os [1] bidang dari bidang) {val = reflections.invoketter (e, ((bidang) OS [1]). getName ()); } else if (os [1] Metode instance) {val = reflections.invokemethod (e, ((method) OS [1]). getName (), kelas baru [] {}, objek baru [] {}); }} // Jika dikt, dapatkan label dict if (stringutils.isnotblank (ef.dictType ())) {val = dictutils.getdictlabel (val == null? "": Val.toString (), ef.dictType (), ""); }} catch (exception ex) {// gagal mengabaikan log.info (ex.toString ()); val = ""; } this.addcell (baris, colunm ++, val, ef.align (), ef.fieldType ()); SB.Append (val + ","); } log.debug ("Tulis Sukses: ["+row.getRownum ()+"]"+SB.ToString ()); }} kembalikan ini; } / ** * 输出数据流 * @param OS 输出数据流 * / Public ExportExcel Tulis (OutputStream OS) melempar ioException {wb.write (OS); kembalikan ini; } / ** * 输出到客户端 * @param FileName 输出文件名 * / Public ExportExcel Write (respons httpservletResponse, string fileName) melempar ioException {response.reset (); response.setContentType ("Aplikasi/Octet-Stream; Charset = UTF-8"); response.setHeader ("Disposisi Konten", "lampiran; fileName ="+encodes.urlencode (nama file)); tulis (response.getoutputStream ()); kembalikan ini; } / ** * 输出到文件 * @param FileName 输出文件名 * / Public ExportExcel WriteFile (Name String) Melempar FileNotFoundException, IoException {FileOutputStream OS = FileOutputStream baru (name); this.write (OS); kembalikan ini; } / ** * 清理临时文件 * / public exportexcel buang () {wb.dispose (); kembalikan ini; }}导出测试
public static void main (string [] args) melempar lempar {list <string> headerList = lists.newarraylist (); untuk (int i = 1; i <= 10; i ++) {headerlist.add ("表头"+i); } Daftar <string> datasowlist = lists.newarraylist (); untuk (int i = 1; i <= headerlist.size (); i ++) {datasowlist.add ("数据"+i); } Daftar <Daftar <String>> Datalist = lists.NewArrayList (); untuk (int i = 1; i <= 1000000; i ++) {datalist.add (datashowlist); } ExportExcel ee = ExportExcel baru ("表格标题", headerlist); untuk (int i = 0; i <datalist.size (); i ++) {baris baris = ee.addrow (); untuk (int j = 0; j <datalist.get (i) .size (); j ++) {ee.addcell (baris, j, datalist.get (i) .get (j)); }} ee.writefile ("target/export.xlsx"); ee.dispose (); log.debug ("Ekspor Sukses."); }Importexcel.java
/*** Hak Cipta © 2012-2014 <a href = "https://github.com/thinkgem/jeesite"> jeesite </a> Semua hak dilindungi undang-undang. */paket com.thinkgem.jeesite.common.utils.excel; Impor java.io.file; impor java.io.fileinputstream; impor java.io.ioException; import java.io.inputstream; impor java.lang.reflect.field; impor Java.Lang.reflect.method; impor java.util.collections; impor; java.util.list; Impor org.apache.commons.lang3.stringutils; impor org.apache.poi.hssf.usermodel.hssfworkbook; impor org.apache.poi.openxml4j.exceptions.invalidformateSception; impor org.apache.poi.poi.poi.poi.poi.s.poi.poi.s.poi.poi.poi.poi.poi.poi.poi.poi.poi.poi.poi.poi.poi.poi.poi. org.apache.poi.ss.usermodel.dateutil; impor org.apache.poi.ss.usermodel.row; impor org.apache.poi.ss.usermodel.sheet; impor org.apache.poi.ss.usermodel.workbook; impor org.apache.apache.poi.ss.usermodel.workelar; org.slf4j.logger; impor org.slf4j.loggerFactory; impor org.springframework.web.multipart.multipartfile; impor 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.sysyil /** * 导入 excel 文件(支持 “xls” 和 “xlsx” 格式) * @Author thinkgem * @Version 2013-03-10 */kelas publik ImportExcel {private static logger log = loggerFactory.getLogger (importexcel.class); / ** * 工作薄对象 */ buku kerja pribadi WB; / ** * 工作表对象 */ lembar privat; / ** * 标题行号 */ private int headernum; / ** * 构造函数 * @param path 导入文件 , 读取第一个工作表 * @param headernum 标题行号 , 数据行号 = 标题行号 +1 * @throws InvalidFormateException * @throws IoException */ ImportException Public (FILENAME, INT HEADERNUM) Lempar InvalidFormateException, ioException {this (ini headernum) Lempar, FileNe), IoException {this (this this (this (headernum) lemparan); } / ** * 构造函数 * @param path 导入文件对象 , 读取第一个工作表 * @param headernum 标题行号 , 数据行号 = 标题行号 +1 * @throws InvalidFormateException * @throws IoException * / public ImportExcel (file, headernum) lemparan InvalidFormateException, ioException {this (File, this (File, 0) HEAD (); } /** * 构造函数 * @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(File file, int headerNum, int sheetIndex) throws InvalidFormatException, IOException { this(file.getName(), new FileInputStream (file), headernum, sheetIndex); } / ** * 构造函数 * @param File 导入文件对象 * @param headernum 标题行号 , 数据行号 = 标题行号 +1 * @param sheetIndex 工作表编号 * @throws InvalidFormateException * @throws IoException * / Public ImportExcel (multipartfile MultipartFile, int headernum, int sheetindex) throwsformcel Public (MultipartFile, headernum, int sheetindex) throwsformscel (MultipartFile, headernum, int sheetindex) throwsformscel PUBLIK (MultipARTFILE, INT HEADERNUM, INT Sheetindex) Throwscrorming InvalindExcept this (multipartFile.getoriginalFileName (), multipartfile.getInputStream (), headernum, sheetIndex); } /** * 构造函数 * @param path 导入文件对象 * @param headerNum 标题行号,数据行号=标题行号+1 * @param sheetIndex 工作表编号 * @throws InvalidFormatException * @throws IOException */ public ImportExcel(String fileName, InputStream is, int headerNum, int sheetIndex) throws InvalidFormatException, IOException { if (Stringutils.isblank (nama file)) {lempar runtimeException baru ("导入文档为空!"); } else if (filename.tolowercase (). endswith ("xls")) {this.wb = new hssfworkbook (IS); } else if (filename.tolowercase (). endswith ("xlsx")) {this.wb = new xssfworkbook (IS); } else {lempar runimeException baru ("文档格式不正确!"); } if (this.wb.getNumberofsheets () <sheetIndex) {lempar runimeException baru ("文档中没有工作表!"); } this.sheet = this.wb.getsheetat (sheetIndex); this.headernum = headernum; log.debug ("inisialisasi kesuksesan."); } / ** * 获取行对象 * @param rownum * @return * / baris publik 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 baris 获取的行 * @param kolom 获取单元格列号 * @return 单元格值 * / objek publik getCellValue (baris baris, kolom int) {objek val = ""; coba {sel sel = row.getCell (kolom); 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 grup 导入分组 * / PUBLIK <E> DAFTAR <E> getDataList (kelas <E> cls, int ... grup) melempar InstantiationException, IllegalAccessException {List <object []> annotationList = lists.newarrayList (); // Dapatkan bidang bidang anotasi [] fs = cls.getDeclaredFields (); untuk (bidang f: fs) {excelfield ef = f.getannotation (excelfield.class); if (ef! = null && (ef.type () == 0 || ef.type () == 2)) {if (grup! = null && groups.length> 0) {boolean ingroup = false; untuk (int g: grup) {if (ingroup) {break; } untuk (int efg: ef.groups ()) {if (g == efg) {ingroup = true; annotationlist.add (objek baru [] {ef, f}); merusak; }}}} else {annotationlist.add (objek baru [] {ef, f}); }}} // Dapatkan metode anotasi metode [] ms = cls.getDeclaredMethods (); untuk (metode m: ms) {excelfield eF = m.getannotation (excelfield.class); if (ef! = null && (ef.type () == 0 || ef.type () == 2)) {if (grup! = null && groups.length> 0) {boolean ingroup = false; untuk (int g: grup) {if (ingroup) {break; } untuk (int efg: ef.groups ()) {if (g == efg) {ingroup = true; annotationlist.add (objek baru [] {ef, m}); merusak; }}}} else {annotationlist.add (objek baru [] {ef, m}); }}} // Field Sorting Collections.sort (AnnotationList, Comparator Baru <Object []> () {Public int Compare (Object [] O1, Object [] o2) {return new integer (((excelfield) o1 [0]). Sort ()). Compareto (integer baru ((excelfield) o2 [) (0]). O compareto ((Excelfield); //log.debug("Import COMPOL: "+annotationList.size ()); // Dapatkan daftar data Excel <E> datalist = lists.newarraylist (); untuk (int i = this.getDataRownum (); i <this.getLastDataRownum (); i ++) {e e = (e) cls.newinstance (); int kolom = 0; Baris baris = this.getrow (i); StringBuilder SB = StringBuilder baru (); untuk (objek [] os: annotationlist) {objek val = this.getCellValue (baris, kolom ++); if (val! = null) {excelfield ef = (excelfield) os [0]; // Jika tipe dikt, dapatkan nilai dikte jika (stringutils.isnotblank (ef.dictType ())) {val = dictutils.getdictvalue (val.tostring (), ef.dictType (), ""); //log.debug("Dictionary Tipe Nilai: ["+i+", "+colunm+"] "+val); } // Dapatkan Param Type dan ketik cast class <?> Valtype = class.class; if (os [1] bidang dari bidang) {valtype = ((bidang) OS [1]). getType (); } else if (os [1] instanceof Method) {Method Method = ((Method) OS [1]); if ("get" .equals (method.getName (). substring (0, 3))) {valtype = method.getReturnType (); } else if ("atur" .equals (method.getName (). Substring (0, 3))) {valtype = ((Method) OS [1]). GetParametertypes () [0]; }} //log.debug("MerImport Value Tipe: ["+i+", "+Column+"] "+ValType); coba {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 ()); }} lain 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 ("Dapatkan nilai sel ["+i+","+kolom+"] kesalahan:"+ex.toString ()); val = null; } // Atur Nilai Entitas If (OS [1] Instanceof Field) {Reflections.InvokeSetter (E, ((bidang) OS [1]). GetName (), Val); } else if (os [1] instanceof Metode) {string mthodname = ((metode) os [1]). getName (); if ("get" .equals (mthodname.substring (0, 3))) {mthodname = "set"+stringutils.substringafter (mthodname, "get"); } Reflections.invokemethod (e, mthodname, kelas baru [] {valtype}, objek baru [] {val}); }} sb.append (val+","); } datalist.add (e); log.debug ("baca sukses: ["+i+"]"+sb.tostring ()); } return distalist; }}导入测试
public static void main (string [] args) melempar lempar {importexcel ei = new importexcel ("target/export.xlsx", 1); untuk (int i = ei.getDataRownum (); i <ei.getLastDataRownum (); i ++) {baris baris = ei.getrow (i); untuk (int j = 0; j <ei.getLastCellNum (); j ++) {objek val = ei.getCellValue (baris, j); System.out.print (val+","); } System.out.print ("/n"); }}