在java的開源世界中,有兩套比較有影響的API可供使用,一個是POI,一個是jExcelAPI(即jxl)。jxl功能相對POI比較弱一點。
本來使用的是jxl那一套讀取和生成報表的工具,發現該框架不支持插入批註(因爲批註是特殊語法,jxl代碼會解析批註做特定操作)。
轉用POI,以下是一個寫批註的Demo
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.hssf.usermodel.HSSFComment;
import org.apache.poi.hssf.usermodel.HSSFPatriarch;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import java.io.FileOutputStream;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException{
//創建工作簿對象
HSSFWorkbook wb=new HSSFWorkbook();
//創建工作表對象
HSSFSheet sheet=wb.createSheet("我的工作表");
//創建繪圖對象
HSSFPatriarch p=sheet.createDrawingPatriarch();
//創建單元格對象,批註插入到4行,1列,B5單元格
HSSFCell cell=sheet.createRow(4).createCell(1);
//插入單元格內容
cell.setCellValue(new HSSFRichTextString("批註"));
//獲取批註對象
//(int dx1, int dy1, int dx2, int dy2, short col1, int row1, short col2, int row2)
//前四個參數是座標點,後四個參數是編輯和顯示批註時的大小.
HSSFComment comment=p.createComment(new HSSFClientAnchor(0,0,0,0,(short)3,3,(short)5,6));
//輸入批註信息
comment.setString(new HSSFRichTextString("插件批註成功!插件批註成功!"));
//添加作者,選中B5單元格,看狀態欄
comment.setAuthor("toad");
//將批註添加到單元格對象中
cell.setCellComment(comment);
//創建輸出流
FileOutputStream out=new FileOutputStream("writerPostil.xls");
wb.write(out);
//關閉流對象
out.close();
}
}