package com.ningdatech.kqapi.menu;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;  
import org.apache.poi.xssf.usermodel.XSSFWorkbook;  
  
import java.io.FileInputStream;  
import java.io.FileOutputStream;  
import java.io.IOException;  
  
public class ExcelSplitMergedCells {  
    public static void main(String[] args) throws IOException {  
        // 打开Excel文件  
        FileInputStream fis = new FileInputStream("C:\\Users\\PoffyZhang\\Desktop\\8.8柯桥区企业综合服务中心政务服务事项清单.xlsx");
        Workbook workbook = new XSSFWorkbook(fis);  
        Sheet sheet = workbook.getSheetAt(0);  
  
        // 获取合并单元格的范围  
        CellRangeAddress mergedRegion = sheet.getMergedRegion(0); // 0表示第一个合并的单元格  
        int firstRow = mergedRegion.getFirstRow();  
        int lastRow = mergedRegion.getLastRow();  
        int firstCol = mergedRegion.getFirstColumn();  
        int lastCol = mergedRegion.getLastColumn();  
  
        // 取消合并单元格  
        sheet.removeMergedRegion(0);  
        Integer num = 0;
        // 创建新的单元格并复制内容  
        for (int i = firstRow; i <= lastRow; i++) {
            Row row = sheet.getRow(i);  
            for (int j = firstCol; j <= lastCol; j++) {  
                Cell oldCell = row.getCell(j);  
                Cell newCell = row.createCell(j);  
                newCell.setCellType(oldCell.getCellType());  
                switch (oldCell.getCellType()) {  
                    case STRING:  
                        newCell.setCellValue(oldCell.getStringCellValue());  
                        break;  
                    case NUMERIC:  
                        newCell.setCellValue(oldCell.getNumericCellValue());  
                        break;  
                    case BOOLEAN:  
                        newCell.setCellValue(oldCell.getBooleanCellValue());  
                        break;  
                    case FORMULA:  
                        newCell.setCellFormula(oldCell.getCellFormula());  
                        break;  
                    default:  
                        newCell.setCellValue("");  
                }  
            }  
        }  
  
        // 保存修改后的Excel文件  
        fis.close();  
        FileOutputStream fos = new FileOutputStream("C:\\Users\\PoffyZhang\\Desktop\\8.8柯桥区企业综合服务中心政务服务事项清单2.xlsx");
        workbook.write(fos);  
        fos.close();  
    }  
}