公司客戶需要從系統中導出一些帶圖片的excel報表,因爲圖片的大小不固定,所以如果直接放在excel中會導致嚴重變形。公司的客服說以前有個客戶發給她這樣一個excel表格,在excel中顯示小圖片,鼠標放到小圖片後顯示大圖片,鼠標移走後大圖片隱藏(類似html頁面的浮窗)。我讓她把這個excel表格發給我看看,但她說找不到了。我當時覺得不太可能,而且還有很多其它工作需要去完成,所以沒有仔細去研究。最近領導有提到了這個問題,所以去網上查了一下,似乎好像可以通過excel的批註功能來實現,但沒有找到具體的實例,如是乎我就去POI官網去查看API,然後去實踐,最後終於讓我實現了這個功能,下面貼上實踐的例子:
首先從POI官網下載jar包
http://poi.apache.org/download.html
我下載的是最新的測試版:
然後解壓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。
功能效果:
相信上面的說明和代碼已經說的很詳細了,這裏就不在上傳源碼了。
最後希望這篇文章可以幫助到遇到同樣問題的人。