package com.qishenmemingzihaone;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
public class WritePOI {
public static void main(String[] args) throws FileNotFoundException {
//注意:WorkBook 有XSSFWorkbook 和 HSSFWork 两个版本
//建议用后者,也可尝试EasyPOI
//构造方法中可以接受File文件或者文件的字节输入流,此处自己创建表格
Workbook workbook = new XSSFWorkbook();
//创建一张sheet表,表名为 "第一张表"
Sheet sheet1 = workbook.createSheet("第一张表");
//创建第一行 [注意:行数和列数都是从0索引开始的]
Row row = sheet1.createRow(0);
//创建第一列单元格
Cell cell = row.createCell(0);
//为第一个单元格添加数据
//此处的数据可以是多种类型的数据 :字符串 数字 时间 布尔等,此处不一一列举
cell.setCellValue("第一行的第一个单元格");
//设置单元格中字体的颜色为红色
CellStyle cellStyle = workbook.createCellStyle();
//通过workbook获得文字处理类
Font font = workbook.createFont();
font.setColor(Font.COLOR_RED);
cellStyle.setFont(font);
//设置单元格中的批注
Drawing draw = sheet1.createDrawingPatriarch();
//此处八个参数 前四个参数为两个坐标点(从a坐标到b坐标)后四个参数 为 编辑和显示批注时的大小(看需求调整)
Comment comment = draw.createCellComment(new XSSFClientAnchor(1,1,1,1,1,1,1,1));
//输入批注信息
comment.setString(new HSSFRichTextString("插件批注成功!插件批注成功!"));
//添加作者,选中B5单元格,看状态栏
comment.setAuthor("toad");
//将批注添加到单元格对象中
cell.setCellComment(comment);
FileOutputStream fileOutputStream = new FileOutputStream("此处写入本地xlsx文件的地址,例如 'D:\myexcel.xlsx'");
workBook.write(fileOutputStream);
//最后莫要忘记关闭资源
workBook.close();
fileOutputStream.close();
}
}
【小知识点:从excel表中获取数据的时候,如果表中的数据为空,使用getcell()不会返回空字符串,会报空指针】



