Java程序导入 .xls文件 优化
2014-08-23 17:06
477 查看
首先建立注解
xls文件模板 下面以廉政建设导入为例
先建立Vo类
import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface ExcelAnnotation { // excel导出时标题显示的名字,如果没有设置Annotation属性,将不会被导出和导入 public String exportName(); }
xls文件模板 下面以廉政建设导入为例
先建立Vo类
public class PartyOrganizationsVO { @Override public String toString() { return "PartyOrganizationsVO [orgName=" + orgName + ", orgType=" + orgType + ", orgClerk=" + orgClerk + ", members=" + members + ", areaName=" + areaName + "]"; } @ExcelAnnotation(exportName="党组织名称") private String orgName;//党组织名称 @ExcelAnnotation(exportName = "党组织类别") private String orgType;//党组织类别 @ExcelAnnotation(exportName = "党组织书记") private String orgClerk;//党组织书记 @ExcelAnnotation(exportName = "委员") private String members;//委员 @ExcelAnnotation(exportName = "所属辖区") private String areaName; //所属辖区 private String importErrorRecord;//错误记录 public String getOrgName() { return orgName; } public void setOrgName(String orgName) { this.orgName = orgName; } public String getOrgType() { return orgType; } public void setOrgType(String orgType) { this.orgType = orgType; } public String getOrgClerk() { return orgClerk; } public void setOrgClerk(String orgClerk) { this.orgClerk = orgClerk; } public String getMembers() { return members; } public void setMembers(String members) { this.members = members; } public String getAreaName() { return areaName; } public void setAreaName(String areaName) { this.areaName = areaName; } public String getImportErrorRecord() { return importErrorRecord; } public void setImportErrorRecord(String importErrorRecord) { this.importErrorRecord = importErrorRecord; } }
<pre class="java" name="code">import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.apache.poi.hssf.usermodel.HSSFName; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; /** * 通用Excel导入 * * @param <T> */ public class ExcelImport<T> { Class<T> clazz; public ExcelImport(Class<T> clazz) { this.clazz = clazz; } /** * 导入Excel * * @param titleIndex 表头索引 * @param file excel文件 路径 * @param pattern * @return */ public Collection<T> importExcel(int titleIndex, File file, String... pattern) { Collection<T> dist = new ArrayList(); try { /** * 类反射得到调用方法 */ // 得到目标目标类的所有的字段列表 Field filed[] = clazz.getDeclaredFields(); // 将所有标有Annotation的字段,也就是允许导入数据的字段,放入到一个map中 Map fieldmap = new HashMap(); // 循环读取所有字段 for (int i = 0; i < filed.length; i++) { Field f = filed[i]; // 得到单个字段上的Annotation ExcelAnnotation exa = f.getAnnotation(ExcelAnnotation.class); // 如果标识了Annotationd的话 if (exa != null) { // 构造设置了Annotation的字段的Setter方法 String fieldname = f.getName(); String setMethodName = "set" + fieldname.substring(0, 1).toUpperCase() + fieldname.substring(1); // 构造调用的method, Method setMethod = clazz.getMethod(setMethodName, new Class[]{f.getType()}); // 将这个method以Annotaion的名字为key来存入。 fieldmap.put(exa.exportName(), setMethod); } } /** * excel的解析开始 */ // 将传入的File构造为FileInputStream; FileInputStream in = new FileInputStream(file); // // 得到工作表 HSSFWorkbook book = new HSSFWorkbook(in); // // 得到第一页 HSSFSheet sheet = book.getSheetAt(0); // // 得到第一面的所有行 Iterator<Row> row = sheet.rowIterator(); /** * 标题解析 */ // 得到第一行,也就是标题行 Row title = row.next(); for (int i = 1; i < titleIndex; i++) { //获取表头 title = row.next(); } // 得到第一行的所有列 Iterator<Cell> cellTitle = title.cellIterator(); // 将标题的文字内容放入到一个map中。 Map titlemap = new HashMap(); // 从标题第一列开始 // 循环标题所有的列的名称 int i = 0; // 从标题第一列开始 // 循环标题所有的列 while (cellTitle.hasNext()) { Cell cell = cellTitle.next(); String value = cell.getStringCellValue(); titlemap.put(i, value); i = i + 1; } /** * 解析内容行 */ //用来格式化日期的DateFormat SimpleDateFormat sf; if (pattern.length < 1) { sf = new SimpleDateFormat("yyyy-MM-dd"); } else sf = new SimpleDateFormat(pattern[0]); while (row.hasNext()) { // 标题下的第一行 Row rown = row.next(); // 行的所有列 Iterator<Cell> cellbody = rown.iterator(); // 得到传入类的实例 T tObject = clazz.newInstance(); int k = 0; // 遍历一行的列 int size=rown.getLastCellNum();//单元格数 for(int j=0;j<size;j++){ Cell cell = rown.getCell(j, Row.CREATE_NULL_AS_BLANK); // 这里得到此列的对应的标题 String titleString = (String) titlemap.get(k); // 如果这一列的标题和类中的某一列的Annotation相同,那么则调用此类的的set方法,进行设值 if (fieldmap.containsKey(titleString)) { Method setMethod = (Method) fieldmap.get(titleString); //得到setter方法的参数 Type[] ts = setMethod.getGenericParameterTypes(); //只要一个参数 String xclass = ts[0].toString(); //判断参数类型 try { if (xclass.equals("class java.lang.String")) { if (cell.getCellType() == cell.CELL_TYPE_NUMERIC) { //如果是数字,转换成字符串 cell.setCellType(Cell.CELL_TYPE_STRING); setMethod.invoke(tObject, cell.getStringCellValue()); } else { setMethod.invoke(tObject, cell.getStringCellValue()); } } else if (xclass.equals("class java.util.Date")) { 4000 setMethod.invoke(tObject, sf.parse(cell.getStringCellValue())); } else if (xclass.equals("class java.lang.Boolean")) { Boolean boolname = true; if (cell.getStringCellValue().equals("否")) { boolname = false; } setMethod.invoke(tObject, boolname); } else if (xclass.equals("class java.lang.Integer")) { setMethod.invoke(tObject, new Integer(cell.getStringCellValue())); } else if (xclass.equals("class java.lang.Long")) { setMethod.invoke(tObject, new Long(cell.getStringCellValue())); } } catch (Exception ex) { ex.printStackTrace(); continue; } } // 下一列 k = k + 1; } dist.add(tObject); } } catch (Exception e) { e.printStackTrace(); return null; } return dist; } /** * 根据Cell名称导入Excel * * @param titleIndex 表头索引 * @param file excel文件 路径 * @param pattern * @return */ public Collection<T> importExcelByCellName(int titleIndex, Map titlemap, File file, String... pattern) { Collection<T> dist = new ArrayList(); try { /** * 类反射得到调用方法 */ // 得到目标目标类的所有的字段列表 Field filed[] = clazz.getDeclaredFields(); // 将所有标有Annotation的字段,也就是允许导入数据的字段,放入到一个map中 Map fieldmap = new HashMap(); // 循环读取所有字段 for (int i = 0; i < filed.length; i++) { Field f = filed[i]; // 得到单个字段上的Annotation ExcelAnnotation exa = f.getAnnotation(ExcelAnnotation.class); // 如果标识了Annotationd的话 if (exa != null) { // 构造设置了Annotation的字段的Setter方法 String fieldname = f.getName(); String setMethodName = "set" + fieldname.substring(0, 1).toUpperCase() + fieldname.substring(1); // 构造调用的method, Method setMethod = clazz.getMethod(setMethodName, new Class[]{f.getType()}); // 将这个method以Annotaion的名字为key来存入。 fieldmap.put(exa.exportName(), setMethod); } } /** * excel的解析开始 */ // 将传入的File构造为FileInputStream; FileInputStream in = new FileInputStream(file); // // 得到工作表 HSSFWorkbook book = new HSSFWorkbook(in); // // 得到第一页 HSSFSheet sheet = book.getSheetAt(0); // // 得到第一面的所有行 Iterator<Row> row = sheet.rowIterator(); /** * 标题解析 */ // 得到第一行,也就是标题行 Row title = row.next(); for (int i = 1; i < titleIndex; i++) { //获取表头 title = row.next(); } // 得到第一行的所有列 Iterator<Cell> cellTitle = title.cellIterator(); /** * 解析内容行 */ //用来格式化日期的DateFormat SimpleDateFormat sf; if (pattern.length < 1) { sf = new SimpleDateFormat("yyyy-MM-dd"); } else sf = new SimpleDateFormat(pattern[0]); while (row.hasNext()) { // 标题下的第一行 Row rown = row.next(); // 行的所有列 Iterator<Cell> cellbody = rown.cellIterator(); // 得到传入类的实例 T tObject = clazz.newInstance(); int k = 1; // 遍历一行的列 int size=rown.getLastCellNum();//单元格数 for(int j=0;j<size;j++){ Cell cell = rown.getCell(j, Row.CREATE_NULL_AS_BLANK); // 这里得到此列的对应的标题 String titleString = (String) titlemap.get(k); // 如果这一列的标题和类中的某一列的Annotation相同,那么则调用此类的的set方法,进行设值 if (fieldmap.containsKey(titleString)) { Method setMethod = (Method) fieldmap.get(titleString); //得到setter方法的参数 Type[] ts = setMethod.getGenericParameterTypes(); //只要一个参数 String xclass = ts[0].toString(); //判断参数类型 try { if (xclass.equals("class java.lang.String")) { if (cell.getCellType() == cell.CELL_TYPE_NUMERIC) { //如果是数字,转换成字符串 cell.setCellType(Cell.CELL_TYPE_STRING); setMethod.invoke(tObject, cell.getStringCellValue()); } else { setMethod.invoke(tObject, cell.getStringCellValue()); } } else if (xclass.equals("class java.util.Date")) { setMethod.invoke(tObject, sf.parse(cell.getStringCellValue())); } else if (xclass.equals("class java.lang.Boolean")) { Boolean boolname = true; if (cell.getStringCellValue().equals("否")) { boolname = false; } setMethod.invoke(tObject, boolname); } else if (xclass.equals("class java.lang.Integer")) { setMethod.invoke(tObject, new Integer(cell.getStringCellValue())); } else if (xclass.equals("class java.lang.Long")) { setMethod.invoke(tObject, new Long(cell.getStringCellValue())); } } catch (Exception ex) { ex.printStackTrace(); continue; } } // 下一列 k = k + 1; } dist.add(tObject); } } catch (Exception e) { e.printStackTrace(); return null; } return dist; } public static void main(String[] args) { //生成模板 String[] headers = new String[3]; headers[0] = "姓名"; headers[1] = "手机"; headers[2] = "职务"; try { FileOutputStream fileOut = null; SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); // fileOut = new FileOutputStream("E:/" + df.format(new Date()) + ".xls"); // ExcelUtils.createTemplate(fileOut,headers); // fileOut.close(); } catch (Exception ex) { ex.printStackTrace(); } } }
public class TestImportParty extends TestCase{ /** * 党组织信息导入测试 */ @Test public void testPartyImport() { ExcelImport<PartyOrganizationsVO> test = new ExcelImport(PartyOrganizationsVO.class); File file = new File("E:\\导入\\党组织信息导入模版.xls"); Long befor = System.currentTimeMillis(); List<PartyOrganizationsVO> result = (ArrayList) test.importExcel(2,file); Long after = System.currentTimeMillis(); System.out.println("此次操作共耗时:" + (after - befor) + "毫秒"); if(result!=null) { for (int i = 0; i < result.size(); i++) { PartyOrganizationsVO stu = result.get(i); System.out.println(stu.toString()); } } System.out.println("共转化为List的行数为:" + result.size()); } }
相关文章推荐
- java操作txt或xls文件批量导入数据
- 使用POI实现在java程序中导入导出Excel文件数据
- java操作txt或xls文件批量导入数据
- Java程序导入文本文件生成XLS格式
- java poi导入EXCEL xls文件代码
- java导入Excel包含多张sheet表的.xls .xslx .txt三种后缀格式的文件
- java 导入xls文件
- java 导入Excel 文件,兼容Excel 2003(后缀名:xls)及 2007(后缀名:xlsx)的文件,同时还支持csv格式的文件
- Java 导入 xls,xlsx 文件数据
- java xls文件数据导入
- java实现xls/csv文件导入
- java操作txt或xls文件批量导入数据
- java xls文件数据导入
- Java程序导入文本文件生成XLS格式
- Java实现文件批量导入导出实例(兼容xls,xlsx)
- 完美解决Java程序在 MOTO E680i 中声音文件播放(转载)
- 将DBF,XLS,XML,MDB文件导入C#DataGrid的方法
- 如何将dataSet中的数据导入到Excel文件(*.xls)整理
- Java如何解决Excel导入文件时科学计数问题
- Asp.Net下导出/导入规则的Excel(.xls)文件