excel文件读取
方法一
import java.io.IOException; import java.io.InputStream; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang.StringUtils; import org.apache.poi.hssf.usermodel.HSSFCell; 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.ss.usermodel.Cell; 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 ImportExcelUtil { private final static String excel2003L =".xls"; //2003- 版本的excel private final static String excel2007U =".xlsx"; //2007+ 版本的excel /** * 描述:获取IO流中的数据,组装成List<List<Object>>对象 * @param in,fileName * @return * @throws IOException */ public List<List<Object>> getBankListByExcel(InputStream in,String fileName) throws Exception{ List<List<Object>> list = null; //创建Excel工作薄 Workbook work = this.getWorkbook(in,fileName); if(null == work){ throw new Exception("创建Excel工作薄为空!"); } list = new ArrayList<List<Object>>(); String fileType = fileName.substring(fileName.lastIndexOf(".")); if(excel2003L.equals(fileType)){ HSSFRow row = null; HSSFSheet sheet = null; HSSFCell cell = null; //遍历Excel中所有的sheet for (int i = 0; i < work.getNumberOfSheets(); i++) { sheet = (HSSFSheet) work.getSheetAt(i); if(sheet==null){continue;} //遍历当前sheet中的所有行 int cells = sheet.getRow(0).getLastCellNum(); int rows = sheet.getLastRowNum(); for (int j = 1; j <= rows; j++) { row = sheet.getRow(j); if(row==null || isBlankRow(row)){continue;} //遍历所有的单元格 List<Object> li = new ArrayList<Object>(); for (int y = 0; y < cells; y++) { cell = row.getCell(y); if(StringUtils.isNotEmpty(cell == null ? "" : cell.toString())){ li.add(this.getCellValue(cell)); }else{ li.add(""); } } list.add(li); } } }else if(excel2007U.equals(fileType)){ Sheet sheet = null; Row row = null; Cell cell = null; //遍历Excel中所有的sheet for (int i = 0; i < work.getNumberOfSheets(); i++) { sheet = work.getSheetAt(i); if(sheet==null){continue;} //遍历当前sheet中的所有行 int rows = sheet.getLastRowNum(); for (int j = 1; j <= rows; j++) { row = sheet.getRow(j); if(row==null){continue;} //遍历所有的单元格 List<Object> li = new ArrayList<Object>(); int cells = row.getLastCellNum(); for (int y = 0; y < cells; y++) { cell = row.getCell(y); if(StringUtils.isNotEmpty(cell == null ? "" : cell.toString())){ li.add(this.getCellValue(cell)); }else{ li.add(""); } } list.add(li); } } } return list; } public static boolean isBlankRow(HSSFRow row){ if(row == null) return true; boolean result = true; for(int i = row.getFirstCellNum(); i < row.getLastCellNum(); i++){ HSSFCell cell = row.getCell(i, HSSFRow.RETURN_BLANK_AS_NULL); String value = ""; if(cell != null){ switch (cell.getCellType()) { case Cell.CELL_TYPE_STRING: value = cell.getStringCellValue(); break; case Cell.CELL_TYPE_NUMERIC: value = String.valueOf((int) cell.getNumericCellValue()); break; case Cell.CELL_TYPE_BOOLEAN: value = String.valueOf(cell.getBooleanCellValue()); break; case Cell.CELL_TYPE_FORMULA: value = String.valueOf(cell.getCellFormula()); break; //case Cell.CELL_TYPE_BLANK: // break; default: break; } if(!value.trim().equals("")){ result = false; break; } } } return result; } /** * 描述:根据文件后缀,自适应上传文件的版本 * @param inStr,fileName * @return * @throws Exception */ public Workbook getWorkbook(InputStream inStr,String fileName) throws Exception{ Workbook wb = null; String fileType = fileName.substring(fileName.lastIndexOf(".")); if(excel2003L.equals(fileType)){ wb = new HSSFWorkbook(inStr); //2003- }else if(excel2007U.equals(fileType)){ wb = new XSSFWorkbook(inStr); //2007+ }else{ throw new Exception("解析的文件格式有误!"); } return wb; } /** * 描述:对表格中数值进行格式化 * @param cell * @return */ public Object getCellValue(Cell cell){ Object value = null; DecimalFormat df = new DecimalFormat("0"); //格式化number String字符 SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd"); //日期格式化 DecimalFormat df2 = new DecimalFormat("0.00"); //格式化数字 switch (cell.getCellType()) { case Cell.CELL_TYPE_STRING: value = cell.getRichStringCellValue().getString(); break; case Cell.CELL_TYPE_NUMERIC: if("General".equals(cell.getCellStyle().getDataFormatString())){ value = df.format(cell.getNumericCellValue()); }else if("m/d/yy".equals(cell.getCellStyle().getDataFormatString())){ value = sdf.format(cell.getDateCellValue()); }else{ value = df2.format(cell.getNumericCellValue()); } break; case Cell.CELL_TYPE_BOOLEAN: value = cell.getBooleanCellValue(); break; case Cell.CELL_TYPE_BLANK: value = ""; break; default: break; } return value; } }
方法二
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.DateUtil; 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.ss.usermodel.WorkbookFactory; public class ExcelReader { Workbook wb = null; public Workbook getWb() { return wb; } public void setWb(Workbook wb) { this.wb = wb; } List<String[]> dataList = new ArrayList<String[]>(100); public ExcelReader(String path) { try { createWorkbook(new FileInputStream(path)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public ExcelReader(FileInputStream fs) { createWorkbook(fs); } private void createWorkbook(FileInputStream fs) { try { InputStream inp = fs; wb = WorkbookFactory.create(inp); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (InvalidFormatException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /** * 取Excel所有数据,包含header * * @return List<String[]> */ public List<String[]> getAllData(int sheetIndex, boolean isOnlyReadHeader) { int columnNum = 0; Sheet sheet = wb.getSheetAt(sheetIndex); if (sheet.getRow(0) != null) { columnNum = sheet.getRow(0).getLastCellNum() - sheet.getRow(0).getFirstCellNum(); } if (columnNum > 0) { for (Row row : sheet) { String[] singleRow = new String[columnNum]; int n = 0; for (int i = 0; i < columnNum; i++) { Cell cell = row.getCell(i, Row.CREATE_NULL_AS_BLANK); switch (cell.getCellType()) { case Cell.CELL_TYPE_BLANK: singleRow[n] = ""; break; case Cell.CELL_TYPE_BOOLEAN: singleRow[n] = Boolean.toString(cell.getBooleanCellValue()); break; // 数值 case Cell.CELL_TYPE_NUMERIC: if (DateUtil.isCellDateFormatted(cell)) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // singleRow[n] = String.valueOf(cell // .getDateCellValue()); singleRow[n] = sdf.format(cell.getDateCellValue()); } else { cell.setCellType(Cell.CELL_TYPE_STRING); String temp = cell.getStringCellValue(); // 判断是否包含小数点,如果不含小数点,则以字符串读取,如果含小数点,则转换为Double类型的字符串 if (temp.indexOf(".") > -1) { singleRow[n] = String.valueOf(new Double(temp)).trim(); } else { singleRow[n] = temp.trim(); } } break; case Cell.CELL_TYPE_STRING: singleRow[n] = cell.getStringCellValue().trim(); break; case Cell.CELL_TYPE_ERROR: singleRow[n] = ""; break; case Cell.CELL_TYPE_FORMULA: cell.setCellType(Cell.CELL_TYPE_STRING); singleRow[n] = cell.getStringCellValue(); if (singleRow[n] != null) { singleRow[n] = singleRow[n].replaceAll("#N/A", "").trim(); } break; default: singleRow[n] = ""; break; } n++; } if ("".equals(singleRow[0])) { Boolean isAllEmpty = true; for (String str : singleRow) { if (StringUtils.isNotBlank(str)) { isAllEmpty = false; break; } } if (isAllEmpty) { continue; } } // 如果第一行为空,跳过 dataList.add(singleRow); if (isOnlyReadHeader) { break; } } } return dataList; } /** * 返回Excel最大行index值,实际行数要加1 * * @return */ public int getRowNum(int sheetIndex) { Sheet sheet = wb.getSheetAt(sheetIndex); return sheet.getLastRowNum(); } /** * 返回数据的列数 * * @return */ public int getColumnNum(int sheetIndex) { Sheet sheet = wb.getSheetAt(sheetIndex); Row row = sheet.getRow(0); if (row != null && row.getLastCellNum() > 0) { return row.getLastCellNum(); } return 0; } /** * 获取某一行数据 * * @param rowIndex * 计数从0开始,rowIndex为0代表header行 * @return */ public String[] getRowData(int sheetIndex, int rowIndex) { if (rowIndex > this.getColumnNum(sheetIndex)) { return null; } else { return this.dataList.get(rowIndex); } } /** * 获取某一列数据 * * @param colIndex * @return */ public String[] getColumnData(int sheetIndex, int colIndex) { String[] dataArray = null; if (colIndex > this.getColumnNum(sheetIndex)) { return dataArray; } else { if (this.dataList != null && this.dataList.size() > 0) { dataArray = new String[this.getRowNum(sheetIndex) + 1]; int index = 0; for (String[] rowData : dataList) { if (rowData != null) { dataArray[index] = rowData[colIndex]; index++; } } } } return dataArray; } }
浙公网安备 33010602011771号