JAVA实现读取Excel中数据

public static void main(String[] args) {
		File file = new File("C:\\Users\\Administrator\\Desktop\\读取测试.xlsx");
		if(file.exists()){
			try {
				Workbook book = WorkbookFactory.create(file);
				List<Object> rowDataList = null ;
				List<List<Object>> allRowDataList = new ArrayList<List<Object>>();
				Sheet sheet = null ; //一个工作表
				Row row = null ; //一行
				Cell cell = null ; //一个单元格
				int maxColumn = 0 ;
				int rowIndex = 1 ;//从0开始计数,由于第一行是标题或字段名,故从第二行即1开始
				int columnIndex = 0 ;
				System.out.println(book.getNumberOfSheets());
				for(int sheetIndex = 0 ; sheetIndex<book.getNumberOfSheets();sheetIndex++){
					//根据sheetIndex循环获取工作表
					sheet = book.getSheetAt(sheetIndex);
					row = sheet.getRow(1); //取第一行来获取最大列值
					if(row==null){
						continue;
					}
					//获取最大列值
					maxColumn = row.getLastCellNum();
					for( ;rowIndex<=sheet.getLastRowNum();rowIndex++ ){
						//获取行
						row = sheet.getRow(rowIndex);
						if(row==null){
							continue;
						}
						rowDataList = new ArrayList<Object>();
						for(columnIndex = row.getFirstCellNum();columnIndex < maxColumn; columnIndex++){
							//获取列
							cell = row.getCell(columnIndex);
							//DecimalFormat format = new  DecimalFormat("#.##");
							//String cellValueStr = format.format(cell.getNumericCellValue());
							//Object cellValue = new BigDecimal(cellValueStr);
							int cellValue = (int)cell.getNumericCellValue();
							rowDataList.add(cellValue);
						}
						allRowDataList.add(rowDataList);
					}
				}
				for(List<Object> list : allRowDataList){
					for(Object arrList : list){
						System.out.println(arrList);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}else{
			System.out.println("文件出错");
		}
		
	}

猜你喜欢

转载自blog.csdn.net/weixin_40162920/article/details/79885525
今日推荐