poi解析excel步骤详解
一、本次解析excel应用场景描述如下:
客户需要批量处理数据,将这些数据按照一定格式写成excel,上传至服务器处理操作
本次示例主要讲解解析 --之前有一个上传的功能,如有不懂可参看http://patronli.iteye.com/blog/2330288
二、示例:
package com.patronli.action; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.poifs.filesystem.POIFSFileSystem; 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.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import com.patronli.StrUil; public class testAction { public void doAnalytic() { try { InputStream ip = new FileInputStream(upload);// 获得(excel)输入流 Workbook wb = null; // poi处理(fileContentType是你上传的excel的文件名,主要用来判断格式) if (fileContentType.endsWith(".xls")) { POIFSFileSystem localPOIFSFileSystem = new POIFSFileSystem(ip); wb = new HSSFWorkbook(localPOIFSFileSystem); } else if (fileContentType.endsWith(".xlsx")) { wb = new XSSFWorkbook(ip); } // 如果有多个sheet,可以讲0改为你想要的那个sheet Sheet sheet = wb.getSheetAt(0); Row row = null; int rows = sheet.getLastRowNum();// 获得总行数 if (rows < 1) { // 可以友情提示用户 } else if (rows > 2000) { // 如果服务器处理能力弱,此时可以提醒用户分批处理 } else { // 得到第0行,用户可以在此行填写表头 row = sheet.getRow(sheet.getFirstRowNum()); //获取当前行的各列 String number = StrUil.getCellStringValue(row.getCell(0)); String cardno = StrUil.getCellStringValue(row.getCell(1)); String remark = StrUil.getCellStringValue(row.getCell(2)); String tele = StrUil.getCellStringValue(row.getCell(3)); if (!"序号".equals(number) || !"收款人银行账号".equals(cardno) || !"备注".equals(remark) || !"手机号".equals(tele)) { // 如果要求使用者按照你的模板,此处可以判断用户使用的到底是不是你要求的格式 // 如果不是可以提示用户 } // 从第二行开始拿到真正的数据 for (int i = sheet.getFirstRowNum() + 1; i <= sheet .getLastRowNum(); i++) { row = sheet.getRow(i); if (row == null) {// 发现有空行 // 可以提示用户,从新上传文档 } // 获取当前行的各列数据 String numberV = StrUil.getCellStringValue(row.getCell(0)); String cardnoV = StrUil.getCellStringValue(row.getCell(1)); String remarkV = StrUil.getCellStringValue(row.getCell(2)); //对于纯数字的数据,可以用下面的方法转换列的属性,防止读成科学计数法 //例如,手机号 row.getCell(3).setCellType(XSSFCell.CELL_TYPE_STRING); String teleV = StrUil.getCellStringValue(row.getCell(3)); // 此时已经可以循环拿到每一行的值,可以将这些值存数据库,验证等等操作 } } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
三、相关jar包如附件所示