JAVA删除excel指定列

首先POI没有提供删除列的API,所以就需要用其他的方式实现。

在 java - Apache POI xls column Remove - Stack Overflow 这里找到了实现方式:

先将该列所有值都清空,然后将该列之后的所有列往前移动。

下面的工具类中 

deleteColumns(InputStream excelStream, List<String> delColumnTitleList)方法实现了批量删除列的逻辑。

import lombok.SneakyThrows;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description
 * @ClassName ExcelUtil
 * @Date 2022/12/23 11:38
 */
public class ExcelUtil {

    /**
     * 获取sheet表头
     * @param sheet
     * @return
     */
    public static List<String> getTitle(Sheet sheet) {
        List<String> titleList = new ArrayList<>();
        if (sheet.getPhysicalNumberOfRows() > 0) {
            Row headerRow = sheet.getRow(0); // 获取第一行(表头行)

            for (int i = 0; i < headerRow.getPhysicalNumberOfCells(); i++) {
                Cell cell = headerRow.getCell(i);
                if (cell != null) {
                    String headerText = cell.getStringCellValue();
                    titleList.add(headerText);
                }
            }
        }
        return titleList;
    }

    /**
     * 删除excel指定列
     * @param excelStream excel流
     * @param delColumnTitleList 需要删除的列的表头
     * @return
     */
    @SneakyThrows
    public static ByteArrayOutputStream deleteColumns(InputStream excelStream, List<String> delColumnTitleList) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        Workbook workbook = new XSSFWorkbook(excelStream);
        // 获取第一个sheet
        Sheet sheet = workbook.getSheetAt(0);
        deleteColumns(sheet, delColumnTitleList);
        workbook.write(outputStream);
        workbook.close();
        outputStream.close();
        return outputStream;
    }

    /**
     * 删除sheet指定的列
     * @param sheet
     * @param delColumnTitleList
     */
    public static void deleteColumns(Sheet sheet, List<String> delColumnTitleList) {
        List<String> titleList = getTitle(sheet);
        for (String delTitle : delColumnTitleList) {
            int i = titleList.indexOf(delTitle);
            if (i >= 0) {
                deleteColumn(sheet, i);
            }
            //由于是循环删除,删除后,列所在位置索引会变化,所以titleList相应也移除删除的列
            titleList.remove(delTitle);
        }
    }

    /**
     * 删除指定列
     * poi没有提供删除指定列的api,所以先将该列清空,然后将后续的列往前移动,这样达到删除列的效果
     * @param sheet
     * @param columnToDelete
     */
    public static void deleteColumn(Sheet sheet, int columnToDelete) {
        int maxColumn = 0;
        for (int r = 0; r < sheet.getLastRowNum() + 1; r++) {
            Row row = sheet.getRow(r);

            // if no row exists here; then nothing to do; next!
            if (row == null) {
                continue;
            }

            // if the row doesn't have this many columns then we are good; next!
            int lastColumn = row.getLastCellNum();
            if (lastColumn > maxColumn) {
                maxColumn = lastColumn;
            }

            if (lastColumn < columnToDelete) {
                continue;
            }

            for (int x = columnToDelete + 1; x < lastColumn + 1; x++) {
                Cell oldCell = row.getCell(x - 1);
                if (oldCell != null) {
                    row.removeCell(oldCell);
                }

                Cell nextCell = row.getCell(x);
                if (nextCell != null) {
                    Cell newCell = row.createCell(x - 1, nextCell.getCellType());
                    cloneCell(newCell, nextCell);
                }
            }
        }

        // Adjust the column widths
        for (int c = 0; c < maxColumn; c++) {
            sheet.setColumnWidth(c, sheet.getColumnWidth(c + 1));
        }
    }

    /**
     * 右边列左移
     */
    private static void cloneCell(Cell cNew, Cell cOld) {
        cNew.setCellComment(cOld.getCellComment());
        cNew.setCellStyle(cOld.getCellStyle());

        switch (cNew.getCellTypeEnum()) {
            case BOOLEAN: {
                cNew.setCellValue(cOld.getBooleanCellValue());
                break;
            }
            case NUMERIC: {
                cNew.setCellValue(cOld.getNumericCellValue());
                break;
            }
            case STRING: {
                //这样不丢样式
                cNew.setCellValue(cOld.getRichStringCellValue());
                break;
            }
            case ERROR: {
                cNew.setCellValue(cOld.getErrorCellValue());
                break;
            }
            case FORMULA: {
                cNew.setCellFormula(cOld.getCellFormula());
                break;
            }
        }

    }

}

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在Java删除Excel,可以使用Apache POI库。下面是一个基本的示例代码: ```java import org.apache.poi.ss.usermodel.*; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; public class DeleteExcelColumnExample { public static void main(String[] args) throws IOException { // 创建工作簿 Workbook workbook = WorkbookFactory.create(new File("example.xlsx")); // 获取工作表 Sheet sheet = workbook.getSheetAt(0); // 删除第3 deleteColumn(sheet, 2); // 保存工作簿 FileOutputStream outputStream = new FileOutputStream("example.xlsx"); workbook.write(outputStream); workbook.close(); outputStream.close(); } // 删除指定 private static void deleteColumn(Sheet sheet, int columnIndex) { for (Row row : sheet) { Cell cell = row.getCell(columnIndex); if (cell != null) { row.removeCell(cell); } // 移动右侧单元格 for (int i = columnIndex + 1; i < row.getLastCellNum(); i++) { Cell rightCell = row.getCell(i); if (rightCell != null) { Cell newCell = row.createCell(i - 1, rightCell.getCellType()); newCell.setCellStyle(rightCell.getCellStyle()); switch (rightCell.getCellType()) { case BLANK: break; case BOOLEAN: newCell.setCellValue(rightCell.getBooleanCellValue()); break; case ERROR: newCell.setCellValue(rightCell.getErrorCellValue()); break; case FORMULA: newCell.setCellFormula(rightCell.getCellFormula()); break; case NUMERIC: newCell.setCellValue(rightCell.getNumericCellValue()); break; case STRING: newCell.setCellValue(rightCell.getStringCellValue()); break; } row.removeCell(rightCell); } } } } } ``` 在这个示例代码中,我们首先使用WorkbookFactory创建了一个工作簿,然后获取了第一个工作表。接着,我们调用deleteColumn方法,传入要删除的索引。deleteColumn方法会遍历工作表的每一行,移除指定的单元格,并将右侧的单元格移动到左侧。最后,我们将修改后的工作簿保存到磁盘上。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值