`

POI实现excell批注背景图片(仿html浮窗显示图片)

阅读更多
POI实现excell批注背景图片(仿html浮窗显示图片)

文章发表日期:2015-03-15 15:13:27


效果图:



首先从POI官网下载jar包
http://poi.apache.org/download.html


我下载的是最新的测试版:
http://poi.apache.org/download.html#POI-3.12-beta1
然后解压zip包


代码:

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
 
import org.apache.poi.hssf.usermodel.HSSFComment;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.ClientAnchor;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Drawing;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.util.IOUtils;
 
public class TestImage {
 
	public static void main(String[] args) throws Exception {
		Workbook wb = new HSSFWorkbook(); //or new HSSFWorkbook();
 
		InputStream is = new FileInputStream("png.png");
	    byte[] bytes = IOUtils.toByteArray(is);
	    //添加一张图片到Workbook,并返回图片索引
	    int pictureIdx = wb.addPicture(bytes, Workbook.PICTURE_TYPE_PNG);
	    is.close();
	    
	    CreationHelper factory = wb.getCreationHelper();
 
	    Sheet sheet = wb.createSheet();
	    
	    Row row   = sheet.createRow(3);
	    Cell cell = row.createCell(5);
	    cell.setCellValue("F4");
 
	    Drawing drawing = sheet.createDrawingPatriarch();
 
	    // When the comment box is visible, have it show in a 1x3 space
	    ClientAnchor anchor = factory.createClientAnchor();
	    //col2-col1的差为anchor对象的列宽
	    anchor.setCol1(cell.getColumnIndex());
	    anchor.setCol2(cell.getColumnIndex()+10);
	    //row2-row1的差为anchor对象的行高
	    anchor.setRow1(row.getRowNum());
	    anchor.setRow2(row.getRowNum()+14);
 
	    // Create the comment and set the text+author
	    HSSFComment comment = (HSSFComment) drawing.createCellComment(anchor);
	    comment.setBackgroundImage(pictureIdx);
	    comment.setAuthor("Apache POI");
 
	    // Assign the comment to the cell
	    cell.setCellComment(comment);
 
	    String fname = "comment-xssf.xls";
	    //if(wb instanceof HSSFWorkbook) fname += "x";
	    FileOutputStream out = new FileOutputStream(fname);
	    wb.write(out);
	    out.close();
	}
}

















转载:https://blog.csdn.net/z562743237/article/details/44277307
--
  • 大小: 331.4 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics