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();
}
}
}