使用Java POI 解析EXCLE

来源:转载

package com.ceshi;import java.io.FileInputStream;import java.util.ArrayList;import java.util.List;import org.apache.poi.hssf.usermodel.HSSFCell;import org.apache.poi.hssf.usermodel.HSSFDateUtil;import org.apache.poi.hssf.usermodel.HSSFRow;import org.apache.poi.hssf.usermodel.HSSFSheet;import org.apache.poi.hssf.usermodel.HSSFWorkbook;import org.apache.poi.poifs.filesystem.POIFSFileSystem;public class DomExcel {/** * 解析EXCLE * @param is * @return */public static List<String[]> parseExcel(FileInputStream is){List<String[]> list = null ;try {POIFSFileSystem fs = new POIFSFileSystem(is);// 创建工作簿HSSFWorkbook workBook = new HSSFWorkbook(fs);//储存Excle的数据list = new ArrayList<String[]>();// 获得Excel中工作表个数//System.out.println("工作表个数 :" + workBook.getNumberOfSheets());for (int i = 0; i < workBook.getNumberOfSheets(); i++) {//System.out.println("第" + i + "个工作表名称:" + workBook.getSheetName(i));// 创建工作表HSSFSheet sheet = workBook.getSheetAt(i);int rows = sheet.getPhysicalNumberOfRows(); // 获得行数if (rows > 0) {sheet.getMargin(HSSFSheet.TopMargin);for (int j = 0; j < rows; j++) { // 行循环HSSFRow row = sheet.getRow(j);if (row != null) {int cells = row.getLastCellNum();// 获得列数String[] fieldValue = new String[cells];for (short k = 0; k < cells; k++) { // 列循环HSSFCell cell = row.getCell(k);String value = "";if (cell != null) {switch (cell.getCellType()) {case HSSFCell.CELL_TYPE_NUMERIC: // 数值型if (HSSFDateUtil.isCellDateFormatted(cell)) {// 如果是date类型则,获取该cell的date值value = HSSFDateUtil.getJavaDate(cell.getNumericCellValue()).toString();} else {// 纯数字value = String.valueOf(cell.getNumericCellValue());}break;//此行表示单元格的内容为string类型 case HSSFCell.CELL_TYPE_STRING: // 字符串型value = cell.getStringCellValue();break;case HSSFCell.CELL_TYPE_FORMULA:// 公式型// 读公式计算值value = String.valueOf(cell.getNumericCellValue());if (value.equals("NaN")) {// 如果获取的数据值为非法值,则转换为获取字符串value = cell.getStringCellValue();}break;case HSSFCell.CELL_TYPE_BOOLEAN:// 布尔value = ""+ cell.getBooleanCellValue();break;//此行表示该单元格值为空 case HSSFCell.CELL_TYPE_BLANK: // 空值value = "";break;case HSSFCell.CELL_TYPE_ERROR: // 故障value = "";break;default:value = cell.getStringCellValue();}}fieldValue[k] = value;}list.add(fieldValue);}}}}} catch (Exception ex) {ex.printStackTrace();}return list;}}



分享给朋友:
您可能感兴趣的文章:
随机阅读: