您的位置:首页 > Web前端 > HTML

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

2015-03-15 15:13 489 查看
              公司客户需要从系统中导出一些带图片的excel报表,因为图片的大小不固定,所以如果直接放在excel中会导致严重变形。公司的客服说以前有个客户发给她这样一个excel表格,在excel中显示小图片,鼠标放到小图片后显示大图片,鼠标移走后大图片隐藏(类似html页面的浮窗)。我让她把这个excel表格发给我看看,但她说找不到了。我当时觉得不太可能,而且还有很多其它工作需要去完成,所以没有仔细去研究。最近领导有提到了这个问题,所以去网上查了一下,似乎好像可以通过excel的批注功能来实现,但没有找到具体的实例,如是乎我就去POI官网去查看API,然后去实践,最后终于让我实现了这个功能,下面贴上实践的例子:

首先从POI官网下载jar包

http://poi.apache.org/download.html

我下载的是最新的测试版:

The latest beta release is Apache POI 3.12-beta1
然后解压zip包

新建JAVA工程,然后将所有jar包导入项目中(为了减少麻烦所以导入了全部jar包),编写测试类,代码如下:

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

项目结构:



  上图中的comment-xssf.xls就是导出的excel。

功能效果:



相信上面的说明和代码已经说的很详细了,这里就不在上传源码了。

最后希望这篇文章可以帮助到遇到同样问题的人。


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  EXCEL JAVA html 图片 poi