一、 概要
Apache POI [1] 是用Java编写的免费开源的跨平台的 Java API,Apache POI提供API给Java程序对Microsoft Office格式档案读和写的功能。POI为“Poor Obfuscation Implementation”的首字母缩写,意为“简洁版的模糊实现”。
二、编写poi
1、导入依赖
<dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>4.0.1</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>4.0.1</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml-schemas</artifactId><version>4.0.1</version></dependency>
2、编写工具类
private static Workbook workbook = null;/*** 判断属于2003 还是2007* @param path* @throws Exception*/private static void isSuf(String path) throws Exception {if(null != path){String[] split = path.split("\\.");String suf = split[split.length - 1];if("xls".equals(suf)){workbook = new HSSFWorkbook(new FileInputStream(path));}if("xlsx".equals(suf)){workbook = new XSSFWorkbook(new FileInputStream(path));}}else{workbook = new XSSFWorkbook();}}
3、编写读取excel
/*** 导入方法* @param path* @throws Exception*/public static void readExcel(String path) throws Exception {isSuf(path);//获取我们的sheet表Sheet sheet = workbook.getSheetAt(0);for(int rowNum = 0;rowNum <= sheet.getLastRowNum(); rowNum++){//获取我们每一行Row row = sheet.getRow(rowNum);for (int cellNum = row.getFirstCellNum();cellNum <= row.getLastCellNum();cellNum++){Cell cell = row.getCell(cellNum);Object cellValue = getCellValue(cell);System.out.println(cellValue.toString());}}}
4、编写导出excel
/*** 导出execl* @param list* @throws Exception*/public static void upload(List<Object> list) throws Exception {isSuf(null);Sheet sheet = workbook.createSheet("账号信息表");Row row = sheet.createRow(list.size());Cell cell = row.createCell(3);cell.setCellValue("你好");CellStyle cellStyle = workbook.createCellStyle();Font font = workbook.createFont();font.setFontName("黑体");font.setBold(true);font.setFontHeightInPoints((short) 28);font.setColor((short) 10);cellStyle.setFont(font);cell.setCellStyle(cellStyle);FileOutputStream fileOutputStream = new FileOutputStream("d:\\账号信息表.xlsx");workbook.write(fileOutputStream);fileOutputStream.close();}
5、其他处理类
private static Object getCellValue(Cell cell) {//1.获取到单元格的属性类型CellType cellType = cell.getCellType();//2.根据单元格数据类型获取数据Object value = null;switch (cellType) {case STRING:value = cell.getStringCellValue();break;case BOOLEAN:value = cell.getBooleanCellValue();break;case NUMERIC:if (DateUtil.isCellDateFormatted(cell)) {//日期格式value = cell.getDateCellValue();} else {//数字value = cell.getNumericCellValue();}break;case FORMULA: //公式value = cell.getCellFormula();break;default:break;}return value;}
