Apache-POI操作Excel的一些小技巧

Apache-POI操作Excel将合并后的单元格全部填充为相同数据的一个实例。

	private static void fillMergedRegion(final Sheet sheet) {
		for (int i = 0; i < sheet.getNumMergedRegions(); i++) {
			int startRow = sheet.getMergedRegion(i).getFirstRow();
			int endRow = sheet.getMergedRegion(i).getLastRow();
			int startColumn = sheet.getMergedRegion(i).getFirstColumn();
			int endColumn = sheet.getMergedRegion(i).getLastColumn();
			String value = getStringValue(sheet.getRow(startRow).getCell(startColumn));

			for (int row = startRow; row <= endRow; row++) {
				for (int column = startColumn; column <= endColumn; column++) {
					sheet.getRow(row).getCell(column).setCellValue(value);
				}
			}
		}
	}


Apache-POI操作Excel获得单元格内容

public static String getStringValue(Cell cell) {
		if (cell == null) {
			return StringConst.EMPTY_STRING;
		}

		// get the type of cell, and transform it
		if (Cell.CELL_TYPE_FORMULA == cell.getCellType()) {
			switch (cell.getCachedFormulaResultType()) {
			// if it is mumeric type
			case Cell.CELL_TYPE_NUMERIC:

				return new DataFormatter().createFormat(cell).format(cell.getNumericCellValue());
				// if it is string type
			case Cell.CELL_TYPE_STRING:
				return cell.getRichStringCellValue().toString();

			}
		}
		return new DataFormatter().formatCellValue(cell);
	}


Apache-POI读取Excel2003和2007/**

/**
	 * Read the Excel File
	 * 
	 * @param file
	 *            Excel File
	 * @throws IOException
	 *             Error handling
	 */
	public DVSExcelReader(File file) throws IOException {
		InputStream inputStream = null;
		try {

			inputStream = new FileInputStream(file);

			if (file.getName().endsWith(".xls")) {
				// Excel 2003
				this.workbook = new HSSFWorkbook(inputStream);
			} else if (file.getName().endsWith(".xlsx")) {
				// Excel 2007
				this.workbook = new XSSFWorkbook(inputStream);
			} else {
				throw new RuntimeException("Wrong file name defined!");
			}

		} finally {
			if (inputStream != null)
				inputStream.close();
		}
	}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值