JAVA POI 简单实现批量修改Excel文件中表头批注内容

JAVA POI 简单实现批量修改Excel文件中表头批注内容:

/**
 * excel文件处理批注
 * @param filePath  文件路径
 * @param sheetName 处理的sheet页名称
 * @param oldContent 需要替换的批注内容
 * @param newContent 替换的批注内容
 */
public static void handleRowCellComment(String filePath, String sheetName, String oldContent, String newContent) {
    File file = new File(filePath);
    //获取文件名  判断文件是.xls 或 .xlsx
    String fileName = file.getName();

    int excelType = 0;
    FileInputStream inputStream = null;
    Workbook wb = null;
    Iterator<Sheet> sheetIterator = null;
    FileOutputStream out = null;
    try {
        inputStream = new FileInputStream(file);
        if (fileName.endsWith("xls")) {
            wb = new HSSFWorkbook(inputStream);
            excelType = 1;
        } else if (fileName.endsWith("xlsx")) {
            wb = new XSSFWorkbook(inputStream);
        }

        //所有的sheet页
        sheetIterator = wb.sheetIterator();
        while (sheetIterator.hasNext()) {
            Sheet sheet = sheetIterator.next();
            if (sheet.getSheetName().endsWith(sheetName)) {
                //获取表头信息
                Row header = sheet.getRow(0);
                if (header != null) {
                    for (int i = 0; i < header.getLastCellNum(); i++) {
                        Cell cell = header.getCell(i);
                        String key = "";
                        String stringComment;
                        //有批注
                        if (cell != null && cell.getCellComment() != null) {
                            //获取批注
                            stringComment = cell.getCellComment().getString().toString();
                            if (stringComment.contains(oldContent)) {
                                stringComment = stringComment.replace(oldContent, newContent);
                            }
                            //写入批注
                            if (excelType == 0) {
                                cell.getCellComment().setString(new XSSFRichTextString(stringComment));
                            }else {
                                cell.getCellComment().setString(new HSSFRichTextString(stringComment));
                            }
                        }
                    }
                }
            }
        }
        out = new FileOutputStream(file);
        wb.write(out);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (out != null) {
            try {
                out.flush();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值