POI写入Excel下拉框[Select选项]

记录部分方法, 操作POI

POI version
<poi.version>3.10-FINAL</poi.version>
<dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>${poi.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>${poi.version}</version>
        </dependency>


1.首先根据路径读取Excel模板

	/**
	 * 读取服务器上面的上传的excel文件
	 * 
	 * @param path
	 * @return
	 */
	public static Workbook readWorkBook(String path) {
		Workbook wb = null;

		try {
			wb = WorkbookFactory.create(new File(path));
		} catch (InvalidFormatException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return wb;
	}


2.获取到workbook后,设置哪些行列是下拉框[Select下拉],并设置数据

public String rewriteExcelTempAtEmp(String instance, String path, String upload) {
		//读取默认模板Excel文件
		Workbook workbook = ExcelUtils.readWorkBook(path);
		Sheet sheet = workbook.getSheetAt(0);
		DataValidationHelper helper = sheet.getDataValidationHelper(); 
		
		//CellRangeAddressList(firstRow, lastRow, firstCol, lastCol)设置行列范围
		CellRangeAddressList addressList = new CellRangeAddressList(3, 500, 17, 17);
		
		//设置下拉框数据
		String[]pos = posStatusName(instance);
		DataValidationConstraint constraint = helper.createExplicitListConstraint(pos); 
		DataValidation dataValidation = helper.createValidation(constraint, addressList);
		
		//处理Excel兼容性问题
		if(dataValidation instanceof XSSFDataValidation) {
			dataValidation.setSuppressDropDownArrow(true);
			dataValidation.setShowErrorBox(true);
		}else {
			dataValidation.setSuppressDropDownArrow(false);
		}
		
		sheet.addValidationData(dataValidation);
		
		String fileName = StringUtils.substringAfterLast(path, "/");
	    String newPath = upload+ExcelUtils.getRename(fileName, false);
	    
	    //由于POI打开读取文件后再保存时bug问题, 只能重新定义一个新的Excel写入数据
	    ExcelUtils.createExcel(workbook, newPath);
	    return newPath;
	}


3.由于workbook读取后,在保存原来excel会出现错误,这个是poi的一个小bug吧,官方
也没有看到怎么解释,只能修改后, 重新命名保存一个新的Excel模板

/**
	 * 根据路径创建Excel
	 * @author lance
	 * 2014年8月13日 下午4:06:10
	 * @param workbook
	 * @param path
	 */
	public static void createExcel(Workbook workbook, String path) {
	    FileOutputStream fileOut = null;
		try {
			fileOut = new FileOutputStream(path);
			workbook.write(fileOut);
		} catch (Exception e) {
			logger.error("Error create excel: ", e.getMessage());
		} finally {
			try {
				if(fileOut != null) {
					fileOut.close();
				}
				
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值