您的位置:首页 > 其它

用JXL插入图片到excel的方法

2011-10-13 10:48 567 查看
jexcelapi是我们操作excel经常用一个工具。http://jexcelapi.sourceforge.net/

我们想在插入图片的时候经常会出现失真,走形的现象。问题主要出在
WritableImage(double x,
double y, double width, double height, java.io.File image)
这个方法。

这边的
width
height
并不是图片的像数数值,而是占据几个单元格的意思。API如下:

public WritableImage(double x,
double y,
double width,
double height,
java.io.File image)

Parameters:
x
- the column number at which to position the image
y
- the row number at which to position the image
width
- the number of columns cells which the image spans
height
- the number of rows which the image spans
image
- the source image file
这就需要我们根据像数值来计算占据几个单元格。这边的数值都是小数。

/**
* 插入图片到EXCEL
*
* @param picSheet sheet
* @param pictureFile 图片file对象
* @param cellRow 行数
* @param cellCol 列数
* @throws Exception 例外
*/
private void addPictureToExcel(WritableSheet picSheet, File pictureFile, String cellRow, String cellCol)
throws Exception {
// 开始位置
double picBeginCol = StringUtil.toInteger(cellCol).intValue() - 1;
double picBeginRow = StringUtil.toInteger(cellRow).intValue() - 1;
// 图片时间的高度,宽度
double picCellWidth = 0.0;
double picCellHeight = 0.0;
// 读入图片
BufferedImage picImage = ImageIO.read(pictureFile);
// 取得图片的像素高度,宽度
int picWidth = picImage.getWidth();
int picHeight = picImage.getHeight();

// 计算图片的实际宽度
int picWidth_t = picWidth * 32;  //具体的实验值,原理不清楚。
for (int x = 0; x < 1234; x++) {
int bc = (int) Math.floor(picBeginCol + x);
// 得到单元格的宽度
int v = picSheet.getColumnView(bc).getSize();
double offset0_t = 0.0;
if (0 == x)
offset0_t = (picBeginCol - bc) * v;
if (0.0 + offset0_t + picWidth_t > v) {
// 剩余宽度超过一个单元格的宽度
double ratio_t = 1.0;
if (0 == x) {
ratio_t = (0.0 + v - offset0_t) / v;
}
picCellWidth += ratio_t;
picWidth_t -= (int) (0.0 + v - offset0_t);
} else { //剩余宽度不足一个单元格的宽度
double ratio_r = 0.0;
if (v != 0)
ratio_r = (0.0 + picWidth_t) / v;
picCellWidth += ratio_r;
break;
}
}
// 计算图片的实际高度
int picHeight_t = picHeight * 15;
for (int x = 0; x < 1234; x++) {
int bc = (int) Math.floor(picBeginRow + x);
// 得到单元格的高度
int v = picSheet.getRowView(bc).getSize();
double offset0_r = 0.0;
if (0 == x)
offset0_r = (picBeginRow - bc) * v;
if (0.0 + offset0_r + picHeight_t > v) {
// 剩余高度超过一个单元格的高度
double ratio_q = 1.0;
if (0 == x)
ratio_q = (0.0 + v - offset0_r) / v;
picCellHeight += ratio_q;
picHeight_t -= (int) (0.0 + v - offset0_r);
} else {//剩余高度不足一个单元格的高度
double ratio_m = 0.0;
if (v != 0)
ratio_m = (0.0 + picHeight_t) / v;
picCellHeight += ratio_m;
break;
}
}
//生成一个图片对象。
WritableImage image = new WritableImage(picBeginCol, picBeginRow,
picCellWidth, picCellHeight, pictureFile);
// 把图片插入到sheet
picSheet.addImage(image);
}


但jxl目前只能支持PNG图片。其他类型的图片的时候需要先转换成png。

还有就是支持excel版本有些局限性。对一写excel的艺术字,输入框等等的数据会丢失。相对来说并不是很好的用的工具。

POI虽然也能够插入图片,但有一个问题就是如果excel模板里面已经有了图片,然后再用POI插入图片的话,原来的图片就会被破坏掉。但这种情况jxl却没有问题。

相对来说是各有优点吧。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: