通用excel导出demo 发表于 2017-05-03 | 分类于 java | | 阅读次数: 通用excel导出demo(利用反射)最近项目后台管理系统好多地方都要用到excel导出。考虑到一次次修改原代码太无聊,各方面拼拼凑凑写出个通用类,传几个参数设定下表头就ok了。对反射的概念和相关api了解又加深了点…代码记录如下:123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113import org.apache.poi.hssf.usermodel.*;import javax.servlet.http.HttpServletResponse;import java.io.IOException;import java.io.OutputStream;import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.util.ArrayList;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;public class PoiTool { /** * * @param list 数据源list * @param beanClass list中Object的Class对象 * @param map 表头名与对应字段集合(需预定义,例{<用户名,username><密码,password>}) * @param response 响应对象 * @throws IllegalAccessException * @throws InstantiationException * @throws InvocationTargetException */ public static void exportExcel(List list, Class beanClass, LinkedHashMap<String, String> map, HttpServletResponse response) throws IllegalAccessException, InstantiationException, InvocationTargetException { int j = 0; String valueStr = ""; HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet sheet = wb.createSheet("sheet1"); HSSFCellStyle style = wb.createCellStyle();//样式 style.setAlignment(HSSFCellStyle.ALIGN_CENTER); HSSFRow row = sheet.createRow(0);//第一行 for (Map.Entry<String, String> m : map.entrySet()) {//导入excel表头 HSSFCell cell = row.createCell(j); cell.setCellValue(m.getKey()); cell.setCellStyle(style); sheet.autoSizeColumn(j); valueStr += m.getValue() + "|";//filed字符串 j++; } valueStr = valueStr.substring(0, valueStr.length() - 1); System.out.println(valueStr); String[] valueArray = valueStr.split("\\|");//filed数组 //通过反射获取对应beanClass中的字段 //并将其转为get方法置入集合中 Field field[] = beanClass.getDeclaredFields(); List<Method> methodlist = new ArrayList<>(); for (int i = 0; i < field.length; i++) { String fieldName = field[i].getName(); StringBuffer methodName = new StringBuffer("get"); methodName.append(fieldName.substring(0, 1).toUpperCase()); methodName.append(fieldName.substring(1)); Method getMethod = null; try { getMethod = beanClass.getMethod(methodName.toString()); } catch (NoSuchMethodException e) { e.printStackTrace(); } methodlist.add(getMethod); } //遍历list,并插入数据 for (int i = 0; i < list.size(); i++) { row = sheet.createRow(i + 1);//创建行,从第二行开始 for (int k = 0; k < valueArray.length; k++) {//遍历column Method getMethod = getCurrentMethod(valueArray[k], methodlist);//获取colunm对应的get方法 if (getMethod.getReturnType().toString().indexOf("int") >= 0) { row.createCell(k).setCellValue((int) getMethod.invoke(list.get(i), new Object[]{})); } else if (getMethod.getReturnType().toString().indexOf("String") >= 0) { row.createCell(k).setCellValue((String) getMethod.invoke(list.get(i), new Object[]{})); } else if (getMethod.getReturnType().toString().indexOf("double") >= 0) { row.createCell(k).setCellValue((double) getMethod.invoke(list.get(i), new Object[]{})); } else if (getMethod.getReturnType().toString().indexOf("float") >= 0) { row.createCell(k).setCellValue((float) getMethod.invoke(list.get(i), new Object[]{})); } } sheet.autoSizeColumn(i); } response.reset(); response.setContentType("application/vnd.ms-excel;charset=gb2312"); response.setHeader("Content-disposition", "attachment;filename=excel.xls"); try { OutputStream outputStream = response.getOutputStream(); wb.write(outputStream); wb.close(); outputStream.flush(); outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } //获取当前column的get方法 public static Method getCurrentMethod(String valueArray, List<Method> methodlist) { if (valueArray != null && methodlist.size() > 0) { for (int i = 0; i < methodlist.size(); i++) { if (methodName(methodlist.get(i).getName()).equals(valueArray)) { return methodlist.get(i); } } } return null; } //处理methodName public static String methodName(String str) { if (str != null) { str = str.substring(3).substring(0, 1).toLowerCase() + str.substring(3).substring(1); return str; } return null; }}