Java 导出Excel时如何添加注释?
我想在一个excel文件中添加注释,并且可以导出打开。有推荐的方案吗?
在Java中,可以使用Apache POI库来创建和操作Excel文件,包括添加注释。以下是一个示例代码,用于在单元格中添加注释:
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileOutputStream;
import java.io.IOException;
public class ExcelCommentExample {
public static void main(String[] args) throws IOException {
Workbook workbook = new XSSFWorkbook(); // 创建新的Excel工作簿
Sheet sheet = workbook.createSheet("Sheet1"); // 创建新的工作表
Row row = sheet.createRow(0); // 创建新的行
Cell cell = row.createCell(0); // 创建新的单元格
cell.setCellValue("Hello, world!"); // 设置单元格的值
// 添加注释
CreationHelper createHelper = workbook.getCreationHelper();
ClientAnchor anchor = createHelper.createClientAnchor();
anchor.setCol1(cell.getColumnIndex());
anchor.setCol2(cell.getColumnIndex() + 1);
anchor.setRow1(row.getRowNum());
anchor.setRow2(row.getRowNum() + 1);
Drawing drawing = sheet.createDrawingPatriarch();
Comment comment = drawing.createCellComment(anchor);
comment.setString(createHelper.createRichTextString("This is a comment"));
cell.setCellComment(comment);
// 保存Excel文件
FileOutputStream fileOut = new FileOutputStream("workbook.xlsx");
workbook.write(fileOut);
fileOut.close();
}
}
这段代码创建了一个新的Excel工作簿,并在其中创建了一个工作表、一行和一列。然后,它使用CreationHelper
和ClientAnchor
对象来设置注释的位置和大小,并使用Drawing
对象将注释添加到单元格中。最后,它将Excel文件保存到磁盘上。
15 回答8.4k 阅读
8 回答6.2k 阅读
1 回答4k 阅读✓ 已解决
3 回答6k 阅读
3 回答2.2k 阅读✓ 已解决
2 回答3.1k 阅读
2 回答3.8k 阅读
可以通过GcExcel,在导出Excel的时候,批量添加注释。
注释 - GcExcel 中文文档Java版 | 服务端高性能表格组件 - 葡萄城
结果如下:
