Java中使用POI进行excel的合并

public class Utils {
	
	private static final int XLS_MAX_ROWS = 65535;
	private static final int XLSX_MAX_ROWS = 1048575;
	
	
	/**
	 * 合并多个 Excel 文件
	 * 
	 * @param mergedFile 合并后的文件
	 * @param files      待合并的文件
	 * @param isXlsx     合并文件类型是否是 xlsx
	 * @throws IOException       合并异常
	 */
	public static void mergeExcel(String tempPath,File mergedFile, List<Long> files, boolean isXlsx) throws IOException {
		if (mergedFile == null || files == null) {
			return;
		}
		try(SXSSFWorkbook mergedWorkbook = new SXSSFWorkbook(100);
			FileOutputStream out = new FileOutputStream(mergedFile)){
			SXSSFSheet newSheet;
			Sheet sheetAt;
			for (Long file : files) {
				int start = 0;
				if (ObjectUtils.isEmpty(file)) {
					continue;
				}
				try (XSSFWorkbook oldWorkbook1 =  new XSSFWorkbook(new FileInputStream(tempPath+File.separator+file+".xlsx"));
					 SXSSFWorkbook oldWorkbook = new SXSSFWorkbook(oldWorkbook1)) {
					newSheet =  mergedWorkbook.createSheet(oldWorkbook.getSheetName(0));
					int oldSheetSize = oldWorkbook.getXSSFWorkbook().getNumberOfSheets();
//					sheetAt = oldWorkbook.getSheetAt(0);
					sheetAt = oldWorkbook.getXSSFWorkbook().getSheetAt(0);
					mergeSheetAllRegion2(sheetAt,newSheet);
					Sheet oldSheet;
					Row oldRow;
					SXSSFRow newRow;
					for (int i = 0; i < oldSheetSize; i++) {
						oldSheet = oldWorkbook.getXSSFWorkbook().getSheetAt(i);
						int oldRowSize = oldSheet.getLastRowNum();
						for (int j = 0; j <= oldRowSize; j++) {
							if (start == (isXlsx ? XLSX_MAX_ROWS : XLS_MAX_ROWS)) {
								start = newSheet.getLastRowNum();
							}
							oldRow = oldSheet.getRow(j);
							if(ObjectUtils.isEmpty(oldRow)) continue;
							for (int k = 0; k < oldRow.getLastCellNum(); k++) {
								newSheet.setColumnWidth(k, oldSheet.getColumnWidth(k));
							}
							newRow = newSheet.createRow(start);
							copyRow(mergedWorkbook,oldWorkbook,oldRow, newRow);
							start++;
						}
					}
					newSheet.flushRows();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			mergedWorkbook.write(out);
			out.flush();
		} catch (Exception e ){
			e.printStackTrace();
		}

	}

	private static void copyRow(Workbook workbookNew,SXSSFWorkbook workbook,Row oldRow, Row newRow) {
		if (ObjectUtils.isEmpty(oldRow)){
			return;
		}
		int rowNum =0;
		try {
			rowNum = oldRow.getRowNum();
			newRow.setZeroHeight(oldRow.getZeroHeight());
			if (1 == rowNum || 0==rowNum){
				newRow.setHeight((short)1000);
			} else {newRow.setHeight(oldRow.getHeight());}
		} catch (Exception e) {
			e.printStackTrace();
		}
		for (int i = oldRow.getFirstCellNum(); i <= oldRow.getLastCellNum(); i++) {
			Cell oldCell = oldRow.getCell(i);
			if(ObjectUtils.isEmpty(oldCell)) continue;
			SXSSFCell cell = (SXSSFCell)newRow.createCell(i);
			if (oldCell.getSheet().isColumnHidden(oldCell.getColumnIndex())) {
				cell.getSheet().setColumnHidden(oldCell.getColumnIndex(),true);
			}
			copyCell(workbookNew,workbook, oldCell, cell);
		}
	}
	
	private static void copyCell(Workbook workbookNew,SXSSFWorkbook workbook,Cell oldCell, Cell newCell) {
		CellStyle cellStyleAt = workbookNew.createCellStyle();
		short format = workbookNew.createDataFormat().getFormat("0.00000");
		CellStyle cellStyle = oldCell.getCellStyle();
		short dataFormat = cellStyle.getDataFormat();
		String dataFormatString = cellStyle.getDataFormatString();
		System.out.println("dataFormatString-----"+dataFormatString);
		DataFormat dataFormat1 = workbookNew.createDataFormat();

		System.out.println(dataFormat);
		// 复制单元格样式
//		cellStyleAt.cloneStyleFrom(oldCell.getCellStyle());
		Font fontAt = workbook.getXSSFWorkbook().getFontAt(oldCell.getCellStyle().getFontIndexAsInt());
		Font font = workbookNew.createFont();
		font.setBold(fontAt.getBold());
		font.setFontHeightInPoints(fontAt.getFontHeightInPoints());
		cellStyleAt.setFont(font);
		cellStyleAt.setAlignment(oldCell.getCellStyle().getAlignment());
		cellStyleAt.setVerticalAlignment(oldCell.getCellStyle().getVerticalAlignment());
		if (dataFormatString.startsWith("0")){
			String substring = dataFormatString;
			short format1 = dataFormat1.getFormat(substring);
			System.out.println(substring);
			cellStyleAt.setDataFormat(format1);
		}

		if (oldCell.getCellComment() != null) {
			newCell.setCellComment(oldCell.getCellComment());
		}
		// 不同数据类型处理
		CellType tmpCellType = oldCell.getCellType();
		if(tmpCellType != CellType.FORMULA){
			newCell.setCellType(tmpCellType);
		}
		switch (oldCell.getCellTypeEnum()) {
			case FORMULA:
				if (oldCell.getCellFormula().startsWith("DATEVALUE")){
					newCell.setCellFormula("=E2");
				}else {
					newCell.setCellFormula(oldCell.getCellFormula());
				}

//				cellStyleAt.setDataFormat(format);
				break;
			case NUMERIC:
				if (DateUtil.isCellDateFormatted(oldCell)) {
					newCell.setCellValue(cn.hutool.core.date.DateUtil.formatDate(oldCell.getDateCellValue()));
					newCell.setCellType(CellType.NUMERIC);
				} else {
					newCell.setCellValue(oldCell.getNumericCellValue());
					newCell.setCellType(CellType.NUMERIC);
				}
//				cellStyleAt.setDataFormat(format);
				break;
			case BLANK:
				newCell.setCellValue(oldCell.getStringCellValue());
				break;
			case BOOLEAN:
				newCell.setCellValue(oldCell.getBooleanCellValue());
				break;
			case STRING:
				String stringCellValue = oldCell.getStringCellValue();
				if (!ObjectUtils.isEmpty(stringCellValue) && isInteger(stringCellValue)){
//					cellStyleAt.setDataFormat(format);
					newCell.setCellValue(Float.parseFloat(stringCellValue));
					newCell.setCellType(CellType.NUMERIC);
				} else {
					newCell.setCellValue(stringCellValue);
				}
				break;
			default:
				break;
		}
		// 单元格样式
		newCell.setCellStyle(cellStyleAt);
	}


	public static boolean isInteger(String str) {
		Pattern pattern = Pattern.compile("[0-9]*\\.?[0-9]+");
		return pattern.matcher(str).matches();
	}

	public static void mergeSheetAllRegion2(Sheet tmpSheet, Sheet newExcelSheet) {
		int num = tmpSheet.getNumMergedRegions();
		CellRangeAddress cellRange = null;
		for (int i = 0; i < num; i++) {
			cellRange = tmpSheet.getMergedRegion(i);
			newExcelSheet.addMergedRegion(cellRange);
		}
	}
	
}

多个excel合并为一个excel多sheet

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Java POI是一个用于操作Microsoft Office格式文件的开源库,在处理Excel文件时可以使用它来实现单元格的合并和数据读取。下面是一个使用Java POI合并单元格并读取数据的示例: 1. 导入Java POI的相关库: ```java import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.FileInputStream; import java.io.IOException; ``` 2. 定义一个方法来读取Excel文件: ```java public static void readExcel(String filePath) { try { FileInputStream fileInputStream = new FileInputStream(filePath); Workbook workbook = new XSSFWorkbook(fileInputStream); Sheet sheet = workbook.getSheetAt(0); // 循环遍历每一行 for (Row row : sheet) { // 循环遍历每一列 for (Cell cell : row) { // 判断单元格的合并状态 if (cell.getCellType() == CellType.STRING && cell.getCellStyle().getAlignment() == HorizontalAlignment.CENTER) { // 获取合并区域的开始行、结束行、开始列、结束列 int firstRow = sheet.getMergedRegion(cell.getColumnIndex(), cell.getRowIndex()).getFirstRow(); int lastRow = sheet.getMergedRegion(cell.getColumnIndex(), cell.getRowIndex()).getLastRow(); int firstColumn = sheet.getMergedRegion(cell.getColumnIndex(), cell.getRowIndex()).getFirstColumn(); int lastColumn = sheet.getMergedRegion(cell.getColumnIndex(), cell.getRowIndex()).getLastColumn(); // 获取合并区域的数据 String mergedData = sheet.getRow(firstRow).getCell(firstColumn).getStringCellValue(); // 打印合并区域的数据 System.out.println(mergedData); } } } workbook.close(); fileInputStream.close(); } catch (IOException e) { e.printStackTrace(); } } ``` 3. 调用readExcel方法来读取Excel文件: ```java public static void main(String[] args) { readExcel("excelFile.xlsx"); } ``` 以上就是使用Java POI合并单元格并读取数据的一个简单示例。通过判断单元格的合并状态,可以获取到合并区域的数据。根据具体的需求可以进一步处理合并区域的数据。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值