/**
* @param wb excel
* @return sheet集合<row集合<cell集合,全转为String类型>>
*/
public static List<List<List<String>>> getExcelData(XSSFWorkbook wb){
int numSheets = wb.getNumberOfSheets();
List<List<List<String>>> sheets = new ArrayList<>();
//sheet
for(int i=0;i<numSheets;i++){
XSSFSheet sheet = wb.getSheetAt(i);
System.out.println(sheet.getSheetName());
int numRows = sheet.getLastRowNum();
List<List<String>> rows = new ArrayList<>();
//row
for (int j=0;j<numRows;j++){
XSSFRow row = sheet.getRow(j);
if (row==null){
break;
}
int numCells = row.getLastCellNum();
List<String> cells = new ArrayList<>();
//cell
for (int k=0;k<numCells;k++){
cells.add(getValue(k,row));
}
rows.add(cells);
}
sheets.add(rows);
}
return sheets;
}
/**
* 获取指定位置的数据值,全转为string
* @param rowNum 所属行, 第一行为0
* @param colNum 所诉列, 第一列为0
* @return 值
*/
public static String getValue(int rowNum, int colNum, XSSFSheet sheet){
XSSFRow row = sheet.getRow(rowNum);
return getValue(colNum, row);
}
public static String getValue(int colNum, XSSFRow row){
XSSFCell cell = row.getCell(colNum);
if (cell==null){
return "";
}
String cellValue = "";
CellType cellTypeEnum = cell.getCellTypeEnum();
try {
DecimalFormat df = new DecimalFormat("0.00");
if (cell.getCellTypeEnum() == CellType.NUMERIC) {
if (HSSFDateUtil.isCellDateFormatted(cell)) {
cellValue = DateFormatUtils.format(cell.getDateCellValue(), "yyyy-MM-dd");
} else {
NumberFormat nf = NumberFormat.getInstance();
cellValue = String.valueOf(nf.format(cell.getNumericCellValue())).replace(",", "");
}
} else if (cell.getCellTypeEnum() == CellType.STRING) {
cellValue = String.valueOf(cell.getStringCellValue());
} else if (cell.getCellTypeEnum() == CellType.BOOLEAN) {
cellValue = String.valueOf(cell.getBooleanCellValue());
} else if (cell.getCellTypeEnum() == CellType.ERROR) {
cellValue = "错误类型";
} else if (cell.getCellTypeEnum() == CellType.FORMULA) {//公式类型
cellValue = df.format(cell.getNumericCellValue());//将公式类型的值转成保留两位小数的数字
// cellValue = String.valueOf(cell.getArrayFormulaRange().getNumberOfCells());
} else {
cellValue = "";
}
}catch (Exception e){
logger.error(e.getMessage(),e);
cellValue = "-9999999999";
}
return cellValue;
}
XSSFWorkbook获取excel的值,封装成list集合
最新推荐文章于 2024-04-21 12:15:03 发布