【JAVA】poi,easy excel 导出删除指定列

 注:数据量太大了不建议使用,速度慢

 /**
     * 删除列
     * @param sheet
     * @param columnToDelete
     */
    public static void deleteColumn(Sheet sheet, int columnToDelete) {
        System.out.println(sheet.getLastRowNum());
        for (int r = 0; r <= sheet.getLastRowNum(); r++) {
            Row row = sheet.getRow(r);
            for (int c = columnToDelete; c <= row.getLastCellNum(); c++) {
                Cell cOld = row.getCell(c);
                if (cOld != null) {
                    row.removeCell(cOld);
                }
                Cell cNext = row.getCell(c + 1);
                if (cNext != null) {
                    Cell cNew = row.createCell(c, cNext.getCellType());
                    cloneCell(cNew, cNext);
                     if (r == 0) {
                        sheet.setColumnWidth(c, sheet.getColumnWidth(c + 1));
                     }
                }
            }
        }
    }

    /**
     * 右边列左移,样式值设置
     * @param cNew
     * @param cOld
     */
    private static void cloneCell(Cell cNew, Cell cOld) {
        cNew.setCellComment(cOld.getCellComment());
        cNew.setCellStyle(cOld.getCellStyle());

        if (CellType.BOOLEAN == cNew.getCellType()) {
            cNew.setCellValue(cOld.getBooleanCellValue());
        } else if (CellType.NUMERIC == cNew.getCellType()) {
            cNew.setCellValue(cOld.getNumericCellValue());
        } else if (CellType.STRING == cNew.getCellType()) {
            cNew.setCellValue(cOld.getStringCellValue());
        } else if (CellType.ERROR == cNew.getCellType()) {
            cNew.setCellValue(cOld.getErrorCellValue());
        } else if (CellType.FORMULA == cNew.getCellType()) {
            cNew.setCellValue(cOld.getCellFormula());
        }
    }

 测试删除

  @Test
    public void listFill() {
        String fileName = "E:\\" + "listFill01.xlsx";
        XSSFWorkbook xssfWorkbook = null;
        try {
            xssfWorkbook = new XSSFWorkbook(new FileInputStream(fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }

        //获取需要删除的Sheet
        Sheet sheet = xssfWorkbook.getSheetAt(0);
        //删除第100列
        WorkBookUtil.deleteColumn(sheet, 100);
        try (OutputStream fileOut = new FileOutputStream(fileName)) {
            xssfWorkbook.write(fileOut);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 9
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

天空~华

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值