使用poi复制指定行的内容并插入

本文介绍了使用Java通过FileInputStream操作Excel文件,读取数据,定位特定行(&dataEnd)并创建新行进行数据和样式的复制,包括公式复制的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

上代码


        FileInputStream in = new FileInputStream(new File("xxxx\\测试.xlsx"));
        //通过输入流读取指定的Excel文件
        XSSFWorkbook workbook = new XSSFWorkbook(in);
        //获取Excel文件的第1个Sheet页
        Sheet sheet = workbook.getSheetAt(0);
        int dataEnd = 0;
        for (Row row : sheet) {
            for (Cell cell : row) {
                if (cell.getCellType().equals(CellType.STRING)) {
            //这里的DATA_END为final static String DATA_END = "&dataEnd"; 
            //&dataEnd 是我在xlsx文件中的标识用来获取这个标识定位
                    if (cell.getRichStringCellValue().getString().equals(DATA_END)) {
                        dataEnd = cell.getRowIndex();
                    }
                }
            }
        }
       
        sheet.shiftRows(dataEnd, sheet.getLastRowNum(), 1, true, false);
        Row previousRow = sheet.getRow(dataEnd - 1);
        CellStyle rowStyle = previousRow.getRowStyle();
        // 创建新行并复制样式和数据
        Row newRow = sheet.createRow(dataEnd);
        newRow.setRowStyle(rowStyle);

        for (int i = 0; i < previousRow.getLastCellNum(); i++) {
            Cell oldCell = previousRow.getCell(i);
            Cell newCell = newRow.createCell(i);
            if (oldCell != null) {
                newCell.setCellStyle(oldCell.getCellStyle());
                switch (oldCell.getCellType()) {
                    case BLANK:
                        break;
                    case BOOLEAN:
                        newCell.setCellValue(oldCell.getBooleanCellValue());
                        break;
                    case ERROR:
                        newCell.setCellErrorValue(oldCell.getErrorCellValue());
                        break;
                    case FORMULA:
                        //注意这里复制的函数也跟上一行的相等  这里需要自己处理
                        //目前我还没想到怎么填充公式下来 ┭┮﹏┭┮
                        System.out.println(oldCell.getCellFormula());
                        newCell.setCellFormula(oldCell.getCellFormula()); // 复制公式
                        break;
                    case NUMERIC:
                        newCell.setCellValue(oldCell.getNumericCellValue());
                        break;
                    case STRING:
                        newCell.setCellValue(oldCell.getStringCellValue());
                        break;
                }
            }
        }
        FileOutputStream fileOut = new FileOutputStream("xxxxx\\测试1.xlsx");
        workbook.write(fileOut);
        fileOut.close();
        workbook.close();
        in.close();

图中&dataEnd 就是我要插入数据的位置。

谢谢支持

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值