package cn.com.goldenwater.dcproj.util; import org.apache.commons.lang.StringUtils; import org.apache.poi.hssf.usermodel.HSSFDataFormat; import org.apache.poi.hssf.usermodel.HSSFDateUtil; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; public class ReadExcelUtil { private Logger log = LoggerFactory.getLogger(this.getClass().getName()); public static List readExcelData(File file) { Workbook workbook; int count = 0; try (InputStream is = new FileInputStream(file)) { // 创建文件流 if ("xls".equals(getPostFix(file))) { // xls对应的HSSFWorkbook工作簿对象 workbook = new HSSFWorkbook(is); } else if ("xlsx".equals(getPostFix(file))) { // xlsx对应的XSSFWorkbook工作簿对象 workbook = new XSSFWorkbook(is); } else { return null; } } catch (IOException e) { e.printStackTrace(); return null; } List list = new ArrayList<>(); //循环遍历工作簿里面的sheet表 // for (int i = 0; i < workbook.getNumberOfSheets(); i++) { // 读取第一个工作表 Sheet sheet = workbook.getSheetAt(0); // 為空判斷 if (sheet == null) { return null; } for (int j = 1; j <= sheet.getLastRowNum(); j++) { // 读取每行 Row row = sheet.getRow(j); if (row == null) { continue; } list.add(row); } // } return list; } /** * 获取文件后缀 * * @param file 单元格 * @return 内容 */ private static String getPostFix(File file) { String fileName = file.getName(); if (StringUtils.isBlank(fileName)) { return ""; } if (fileName.contains(".") && fileName.lastIndexOf(".") != fileName.length() - 1) { return fileName.substring(fileName.lastIndexOf(".") + 1); } return ""; } /** * 转换Cell类型的值 * * @param cell 单元格 * @return 内容 */ public static String getValue(Cell cell) { if (null == cell) { return null; } switch (cell.getCellType()) { case BOOLEAN: return String.valueOf(cell.getBooleanCellValue()); case NUMERIC: SimpleDateFormat sdf = null; // 处理日期格式、时间格式 if (HSSFDateUtil.isCellDateFormatted(cell)) { if (cell.getCellStyle().getDataFormat() == HSSFDataFormat.getBuiltinFormat("H:mm")) { sdf = new SimpleDateFormat("HH:mm"); } else { sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); } Date date = cell.getDateCellValue(); return sdf.format(date); } else { DecimalFormat format = new DecimalFormat("#.##"); format.format(cell.getNumericCellValue()); return format.format(cell.getNumericCellValue()); } default: return cell.getStringCellValue(); } } /** * 读取Excel的内容,第一维数组存储的是一行中格列的值,二维数组存储的是多少个行 * * @param file 读取数据的源Excel * @param ignoreRows 读取数据忽略的行数,比喻行头不需要读入 忽略的行数为1 * @return 读出的Excel中数据的内容 * @throws FileNotFoundException * @throws IOException */ public static String[][] getData(File file, int ignoreRows) throws FileNotFoundException, IOException, InvalidFormatException { List result = new ArrayList<>(); int rowSize = 0; BufferedInputStream in = new BufferedInputStream(new FileInputStream( file)); // 打开HSSFWorkbook Workbook wb = WorkbookFactory.create(in); Cell cell = null; for (int sheetIndex = 0; sheetIndex < wb.getNumberOfSheets(); sheetIndex++) { Sheet st = wb.getSheetAt(sheetIndex); // 第一行为标题,不取 for (int rowIndex = ignoreRows; rowIndex <= st.getLastRowNum(); rowIndex++) { Row row = st.getRow(rowIndex); if (row == null) { continue; } int tempRowSize = row.getLastCellNum() + 1; if (tempRowSize > rowSize) { rowSize = tempRowSize; } String[] values = new String[rowSize]; Arrays.fill(values, ""); boolean hasValue = false; for (short columnIndex = 0; columnIndex <= row.getLastCellNum(); columnIndex++) { String value = ""; cell = row.getCell(columnIndex); if (cell != null) { // 设置编码格式 // cell.setEncoding(HSSFCell.ENCODING_UTF_16); switch (cell.getCellType()) { case STRING: value = cell.getStringCellValue(); break; case NUMERIC: if (HSSFDateUtil.isCellDateFormatted(cell)) { Date date = cell.getDateCellValue(); if (date != null) { value = new SimpleDateFormat("yyyy-MM-dd") .format(date); } else { value = ""; } } else { value = new DecimalFormat("0").format(cell .getNumericCellValue()); } break; case FORMULA: // 导入时如果为公式生成的数据则无值 if (!"".equals(cell.getStringCellValue())) { value = cell.getStringCellValue(); } else { value = cell.getNumericCellValue() + ""; } break; case BLANK: break; case ERROR: value = ""; break; case BOOLEAN: value = (cell.getBooleanCellValue() ? "Y" : "N"); break; default: value = ""; } } // 首行不能为空 // if (columnIndex == 0 && "".equals(value.trim())) { // break; // } values[columnIndex] = rightTrim(value); hasValue = true; } if (hasValue) { result.add(values); } } } in.close(); String[][] returnArray = new String[result.size()][rowSize]; for (int i = 0; i < returnArray.length; i++) { returnArray[i] = (String[]) result.get(i); } return returnArray; } /** * 单页,根据head获取数据有效列 * !!!!!!!!!!!!!!!!!!!!!! */ public static String[][] getDataAll(File file, int ignoreRows, int headRowIndex) throws FileNotFoundException, IOException, InvalidFormatException { List result = new ArrayList<>(); BufferedInputStream in = new BufferedInputStream(new FileInputStream(file)); // 打开HSSFWorkbook Workbook wb = WorkbookFactory.create(in); Sheet st = wb.getSheetAt(0); int headRowCellNum = st.getRow(headRowIndex).getLastCellNum(); for (int rowIndex = 0; rowIndex <= st.getLastRowNum(); rowIndex++) { if (rowIndex < ignoreRows) { continue; } else { Row row = st.getRow(rowIndex); System.out.println("-----------------------rowIndex " + rowIndex + "--------------------------------"); String[] values = new String[headRowCellNum]; for (int columnIndex = 0; columnIndex < headRowCellNum; columnIndex++) { String value = ""; System.out.println("----------------------- columnIndex" + columnIndex + "--------------------------------"); Cell cell = row.getCell(columnIndex); if (cell != null) { switch (cell.getCellType()) { case STRING: value = cell.getStringCellValue(); break; case NUMERIC: if (HSSFDateUtil.isCellDateFormatted(cell)) { Date date = cell.getDateCellValue(); if (date != null) { value = new SimpleDateFormat("yyyy-MM-dd") .format(date); } else { value = ""; } } else { value = new DecimalFormat("0").format(cell .getNumericCellValue()); } break; case FORMULA: // 导入时如果为公式生成的数据则无值 try { if (!"".equals(cell.getStringCellValue())) { value = cell.getStringCellValue(); } else { value = cell.getNumericCellValue() + ""; } } catch (Exception e) { value = null; } break; case BLANK: break; case ERROR: value = ""; break; case BOOLEAN: value = (cell.getBooleanCellValue() ? "Y" : "N"); break; default: value = ""; } } values[columnIndex] = value; } result.add(values); } } in.close(); String[][] returnArray = new String[result.size()][headRowCellNum]; for (int i = 0; i < returnArray.length; i++) { returnArray[i] = (String[]) result.get(i); } return returnArray; } /** * 去掉字符串右边的空格 * * @param str 要处理的字符串 * @return 处理后的字符串 */ public static String rightTrim(String str) { if (str == null) { return ""; } int length = str.length(); for (int i = length - 1; i >= 0; i--) { if (str.charAt(i) != 0x20) { break; } length--; } return str.substring(0, length); } }