Apache的POI组件是Java操做Microsoft Office办公套件的强大API,其中对Word,Excel和PowperPoint都有支持,固然使用较多的仍是Excel,由于Word和PowerPoint用程序动态操做的应用较少。本文主要介绍一下Excel的操做方法。java
// 建立字体 HSSFFont font = wb.createFont(); // 设置字体为红色 font.setColor(HSSFFont.COLOR_RED); // 设置字体为粗体 font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 建立单元格格式 HSSFCellStyle cellStyle= wb.createCellStyle(); // 设置字体 cellStyle.setFont(font); // 设置水平居中 cellStyle.setAlignment(CellStyle.ALIGN_CENTER); // 设置垂直靠下 cellStyle.setVerticalAlignment(CellStyle.VERTICAL_BOTTOM); // 设置左边框为双线 cellStyle.setBorderLeft(CellStyle.BORDER_DOUBLE); // 设置背景色为蓝色 cellStyle.setFillBackgroundColor(new HSSFColor.BLUE().getIndex()); // 设置前景色为黄色 cellStyle.setFillForegroundColor(new HSSFColor.YELLOW().getIndex());
POIExcelUtil 类: apache
import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CreationHelper; 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.xssf.usermodel.XSSFWorkbook; public class POIExcelUtil { public static final String FILE_EXTENSION_XLS = "xls"; public static final String FILE_EXTENSION_XLSX = "xlsx"; /** * * @param Map * <String,String> maps 属性表,成员属性age为KEY,中文名称为VALUE * @param List * <T> list 须要导出的数据列表对象 * @param File * file 指定输出文件位置,只能导出excel2003以上版本 * * @return true 导出成功 false 导出失败 */ public static <T> boolean excelExport(Map<String, String> maps, List<T> list, File file) { try { Workbook wb = null; String filename = file.getName(); String type = filename.substring(filename.lastIndexOf(".")+1).toLowerCase(); if (type.equals(FILE_EXTENSION_XLS)) { wb = new HSSFWorkbook(); } if (type.equals(FILE_EXTENSION_XLSX)) { wb = new XSSFWorkbook(); } CreationHelper createHelper = wb.getCreationHelper(); Sheet sheet = wb.createSheet("sheet1"); Set<String> sets = maps.keySet(); Row row = sheet.createRow(0); int i = 0; // 定义表头 for (Iterator<String> it = sets.iterator(); it.hasNext();) { String key = it.next(); Cell cell = row.createCell(i++); cell.setCellValue(createHelper.createRichTextString(maps.get(key))); } // 填充表单内容 System.out.println("--------------------100%"); float avg = list.size() / 20f; int count = 1; for (int j = 0; j < list.size(); j++) { T p = list.get(j); Class classType = p.getClass(); int index = 0; Row row1 = sheet.createRow(j+1); for (Iterator<String> it = sets.iterator(); it.hasNext();) { String key = it.next(); String firstLetter = key.substring(0, 1).toUpperCase(); // 得到和属性对应的getXXX()方法的名字 String getMethodName = "get" + firstLetter+ key.substring(1); // 得到和属性对应的getXXX()方法 Method getMethod = classType.getMethod(getMethodName,new Class[] {}); // 调用原对象的getXXX()方法 Object value = getMethod.invoke(p, new Object[] {}); Cell cell = row1.createCell(index++); cell.setCellValue(value.toString()); } if (j > avg * count) { count++; System.out.print("I"); } if (count == 20) { System.out.print("I100%"); count++; } } FileOutputStream fileOut = new FileOutputStream(file); wb.write(fileOut); fileOut.close(); } catch (IOException e) { e.printStackTrace(); return false; } catch (SecurityException e) { e.printStackTrace(); return false; } catch (NoSuchMethodException e) { e.printStackTrace(); return false; } catch (IllegalArgumentException e) { e.printStackTrace(); return false; } catch (IllegalAccessException e) { e.printStackTrace(); return false; } catch (InvocationTargetException e) { e.printStackTrace(); return false; } return true; } }
POIExcelAnnotation 类:xss
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface POIExcelAnnotation { public String titleName(); }
POIExcelUtil 类:字体
import org.apache.poi.hssf.usermodel.HSSFFont; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.CreationHelper; import org.apache.poi.ss.usermodel.Font; 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.xssf.usermodel.XSSFWorkbook; public class POIExcelUtil { public static final String FILE_EXTENSION_XLS = "xls"; public static final String FILE_EXTENSION_XLSX = "xlsx"; /** * * @param sheetName sheet名称 * @param pojoClass POJO对象类 * @param list 导出数据列表 * @param file file 指定输出文件 * @return true 导出成功 false 导出失败 */ public static <T> boolean excelAnnotationExport(String sheetName ,Class<T> pojoClass,List<T> list, File file) { try { Workbook wb = null; String filename = file.getName(); String type = filename.substring(filename.lastIndexOf(".")+1).toLowerCase(); if (type.equals(FILE_EXTENSION_XLS)) { wb = new HSSFWorkbook(); } if (type.equals(FILE_EXTENSION_XLSX)) { wb = new XSSFWorkbook(); } CreationHelper createHelper = wb.getCreationHelper(); Sheet sheet = wb.createSheet(sheetName); // 标题 List<String> fieldTitle = new ArrayList<String>(); //方法列表,对应表头 List<Method> methodObj = new ArrayList<Method>(); // 获得全部字段 Field fileds[] = pojoClass.getDeclaredFields(); // 遍历整个filed for (int i = 0; i < fileds.length; i++) { Field field = fileds[i]; POIExcelAnnotation annotation = field.getAnnotation(POIExcelAnnotation.class); // 若是设置了annottion if (annotation != null) { // 添加到标题 fieldTitle.add(annotation.titleName()); // 添加到须要导出的字段的方法 String fieldName = field.getName(); String firstLetter = fieldName.substring(0, 1).toUpperCase(); // 得到和属性对应的getXXX()方法的名 String getMethodName = "get" + firstLetter+ fieldName.substring(1); // 得到和属性对应的getXXX()方法 Method getMethod = pojoClass.getMethod(getMethodName,new Class[] {}); methodObj.add(getMethod); } } //设置表头粗体 Font font = wb.createFont(); font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); CellStyle style = wb.createCellStyle(); style.setFont(font); //填充表头内容 Row row = sheet.createRow(0); for(int i=0;i<fieldTitle.size();i++){ String title = fieldTitle.get(i); Cell cell = row.createCell(i); cell.setCellStyle(style); cell.setCellValue(createHelper.createRichTextString(title)); } // 填充表单内容 System.out.println("--------------------100%"); float avg = list.size() / 20f; int count = 1; for (int j = 0; j < list.size(); j++) { T p = list.get(j); Row row1 = sheet.createRow(j+1); for (int k=0;k<methodObj.size();k++) { Method getMethod = methodObj.get(k); Object value = getMethod.invoke(p, new Object[] {}); Cell cell = row1.createCell(k); cell.setCellValue(value.toString()); } if (j > avg * count) { count++; System.out.print("I"); } if (count == 20) { System.out.println("I100%"); count++; } } FileOutputStream fileOut = new FileOutputStream(file); wb.write(fileOut); fileOut.close(); } catch (IOException e) { e.printStackTrace(); return false; } catch (SecurityException e) { e.printStackTrace(); return false; } catch (NoSuchMethodException e) { e.printStackTrace(); return false; } catch (IllegalArgumentException e) { e.printStackTrace(); return false; } catch (IllegalAccessException e) { e.printStackTrace(); return false; } catch (InvocationTargetException e) { e.printStackTrace(); return false; } return true; } }
public static void main(String args[]){ List<JavaBean> demo = ****; Map<String,String> maps = new LinkedHashMap<String,String>(); maps.put("uid", "账号"); maps.put("cn", "姓名"); maps.put("dept", "部门"); maps.put("mail", "邮箱"); Properties props = System.getProperties(); String USER_HOME = props.getProperty("user.home"); File file = new File(USER_HOME + "/Desktop/excelExport.xlsx"); POIExcelUtil.excelExport(maps, demo , file); }
Excel导入:ui
import org.apache.poi.hssf.usermodel.HSSFFont; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.CreationHelper; import org.apache.poi.ss.usermodel.Font; 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.xssf.usermodel.XSSFWorkbook; public class POIExcelUtil { public static final String FILE_EXTENSION_XLS = "xls"; public static final String FILE_EXTENSION_XLSX = "xlsx"; @SuppressWarnings("unchecked") public static List importExcel(File file ){ List list = new ArrayList(); Workbook wb = null; String filename = file.getName(); String type = filename.substring(filename.lastIndexOf(".")+1).toLowerCase(); if (type.equals(FILE_EXTENSION_XLS)) { wb = new HSSFWorkbook(); } if (type.equals(FILE_EXTENSION_XLSX)) { wb = new XSSFWorkbook(); } Sheet sheet = wb.getSheetAt(0); for(int i=1;i<sheet.getLastRowNum();i++){ Row row = sheet.getRow(i); //如下代码,根据需求自由变化 for(int j=0;j<row.getLastCellNum();j++){ Cell cell = row.getCell(j); list.add(cell.getRichStringCellValue().getString()); } } return list; } }