excel poi基本操作

判断一行是否为空

	public static boolean isBlankRow(Row row, Integer startCol, Integer endCol) {
		if (row == null)
			return true;
		boolean result = true;
		for (int i = startCol; i <= endCol; i++) {
			Cell cell = row.getCell(i, Row.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;
				default:
					break;
				}
				if (!value.trim().equals("")) {
					result = false;
					break;
				}
			}
		}
		return result;
	}

下载excel到客户端

	public static void renderExcel(String path,String fileName,HttpServletResponse response) throws Exception{
		if(!fileName.toLowerCase().endsWith(".xls") && !fileName.toLowerCase().endsWith(".xlsx")){
			throw new Exception(fileName+"不是一个合法的excel文件名..............................");
		}
//		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("application/vnd.ms-excel");
	    response.setHeader("Content-disposition","attachment;filename=\""+ new String((fileName).getBytes("UTF-8"),"ISO-8859-1") + "\"");
		OutputStream os = response.getOutputStream();
		FileInputStream fis = new FileInputStream(path);
		byte[] buff = new byte[1024];
		int readCount = 0;
		readCount = fis.read(buff);
		while (readCount != -1) {
			os.write(buff, 0, readCount);
			readCount = fis.read(buff);
		}
		if (fis != null) {
			fis.close();
		}
		if (os != null) {
			os.close();
		}
	}

导出错误的excel

	public String downloadExcel(HttpServletRequest request, HttpServletResponse response) throws Exception {
		File file = new File("D:\\NEWUPLOAD\\\\EXCEL\\result.xlsx");
		if(!file.exists()){
			 savaToExcel(new XSSFWorkbook("D:\\NEWUPLOAD\\EXCEL\\result.xlsx"),"D:\\NEWUPLOAD\\EXCEL\\result.xlsx");//输出到文件
		}
		renderExcel("D:\\NEWUPLOAD\\EXCEL\\result.xlsx","错误明细.xlsx", response);
		return null;
	}
	

将excel保存在本地临时目录

public static void savaToExcel( Workbook workbook,String excelPath){
		try {			
			FileOutputStream outputStream = new FileOutputStream(excelPath);
			workbook.write(outputStream);
			outputStream.flush();
			outputStream.close();
		} catch (Exception e) {
			 System.out.println("It cause Error on WRITTING excel workbook: ");
			e.printStackTrace();
		}
		
	}

对比数据类型

	public String getCellType(Cell cell,String ruleCellType,String dictSql) {
		if (cell == null) return "";
		String message = "";
		String upperRuleType = ruleCellType.toUpperCase();
		if(upperRuleType.equals("DATE")){
			try{
				Object value = getCellValue(cell);
				if(value!=null && !value.toString().equals("")){
					if(!DateUtil.isCellDateFormatted(cell)){  
						//  如果是date类型则 ,获取该cell的date值  
						message = "数据类型应该为日期类型";  
					}
				}
			}catch(Exception e){
				message = "数据类型应该为日期类型";  
			}
		}
		if(upperRuleType.equals("INTEGER")||upperRuleType.equals("NUMBER")){
			try{
				String cellValue = getCellValue(cell).toString();
				Double.parseDouble("".equals(cellValue) ? "0":cellValue);
			}catch(Exception e){
				message = "数据类型应该为数字类型";
			}
		}	
		return message;
    }

刷新Cell 背景颜色

public static void refreshCellBackgroundColor(Workbook wb, Sheet sheet, int startRow, int endRow, int startCell,
			int endCell, CellStyle cellStyle) {
		Row row = null;
		Cell cell = null;
		for (int i = startRow; i <= endRow; i++) {
			row = sheet.getRow(i);
			if (row != null) {
				for (int j = startCell; j <= endCell; j++) {
					cell = row.getCell(j);
					if (cell == null) {
						cell = row.createCell(j);
					}
					if(cell.getCellStyle().getDataFormat()>0){
						CellStyle cellStyle2 = wb.createCellStyle();						
						cellStyle2.cloneStyleFrom(cellStyle);
						//cellStyle2.setDataFormat(cell.getCellStyle().getDataFormat());
						cell.setCellStyle(cellStyle2);						
					}else{
						cellStyle.setDataFormat(cell.getCellStyle().getDataFormat());
						cell.setCellStyle(cellStyle);						
					}

				}
			}
		}
	}

获得cell的数值

	public static Object getCellValue(Cell cell) {
		if(cell==null){
			return "";
		}
		Object result = null;
		switch (cell.getCellType()) {
		case Cell.CELL_TYPE_NUMERIC:
			  if(DateUtil.isCellDateFormatted(cell)){  
			       //如果是date类型则 ,获取该cell的date值  
				   //result = DateUtil.getJavaDate(cell.getNumericCellValue());  
				   result = DateFormatUtils.format(cell.getDateCellValue(), "yyyy/MM/dd"); 
			  }else{ 
				  // 纯数字  
				  //result =new BigDecimal( String.valueOf(cell.getNumericCellValue())).toString();  
				  result =  BigDecimal.valueOf(cell.getNumericCellValue()).stripTrailingZeros().toPlainString();
			  }  
			break;
	        case Cell.CELL_TYPE_STRING :
	            result = cell.getRichStringCellValue().getString().trim();
	            break;
	        case Cell.CELL_TYPE_FORMULA :
	           /* result = cell.getCellFormula(); 使用下面,直接获取值*/ 
	        	DecimalFormat df = new DecimalFormat("#.0000");
	        	result = df.format(cell.getNumericCellValue());
	            break;
	        case Cell.CELL_TYPE_BOOLEAN :
	            result = cell.getBooleanCellValue();
	            break;
	        case Cell.CELL_TYPE_ERROR :
	            result = cell.getErrorCellValue();
	            break;
	        case Cell.CELL_TYPE_BLANK :
	            result = "";
	            break;
	    }
		return result;
    }

获得Excel源

	public static Workbook getWorkbook(InputStream in) throws Exception{
    	errorMsgList = new ArrayList<String>();
		Workbook wb = WorkbookFactory.create(in);
		IOUtils.closeQuietly(in);
		return wb;
	}

猜你喜欢

转载自blog.csdn.net/qq_35029061/article/details/82403746