java编程添加图片,Java编程POI处理Excel中添加图片

import java.io.ByteArrayOutputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import org.apache.poi.ss.usermodel.Sheet;

import org.apache.poi.xssf.usermodel.XSSFClientAnchor;

import org.apache.poi.xssf.usermodel.XSSFDrawing;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExcelPicTest {

public static void main(String[] args) {

try {

// 创建一个excel文件

XSSFWorkbook workbook = new XSSFWorkbook();

// 获取第一个表格

Sheet sheet0 = workbook.createSheet();

// 画图的顶级管理器,一个sheet只能获取一个(一定要注意这点)

XSSFDrawing patriarch = (XSSFDrawing) sheet0.createDrawingPatriarch();

// 图片定位

// 参数说明

// int dx1, int dy1, int dx2, int dy2, int col1, int row1, int col2,

// int row2

// dx1,dy1,dx2,dy2一般用不到,标识单元格内的x,y

// **********************以下四个参数定位图片的具体存放位置*********************

// col1:the column (0 based) of the first cell.

// row1:the row (0 based) of the first cell.

// col2: the column (0 based) of the second cell.

// row2: the row (0 based) of the second cell.

// **********************以上四个参数用来定位两个单元格,都是从索引0开始的************

// col1/row1定位图片开始的左上角位置(包含当前单元格),这里传递的1,1表示图片左上角为第2行(索引从0开始1表示第二行)第二个单元格(索引从0开始1表示第二行)开始

// col2/row2定位图片的右下角位置(不含),这里的8,5标识结束为6行(索引从0开始1表示第二行)第9格单元格(索引从0开始1表示第二行)结束

XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, 1, 1, 8, 5);

//

FileInputStream fis = new FileInputStream(new File("d:/1.jpg"));

byte[] image = input2byte(fis);// 图片

patriarch.createPicture(anchor, workbook.addPicture(image, HSSFWorkbook.PICTURE_TYPE_PNG));// 写图片

// excel文件输出

File excel = new File("d://t1.xlsx");

workbook.write(new FileOutputStream(excel));

workbook.close();

} catch (Exception e) {

e.printStackTrace();

}

}

public static final byte[] input2byte(InputStream inStream) throws IOException {

ByteArrayOutputStream swapStream = new ByteArrayOutputStream();

byte[] buff = new byte[100];

int rc = 0;

while ((rc = inStream.read(buff, 0, 100)) > 0) {

swapStream.write(buff, 0, rc);

}

byte[] in2b = swapStream.toByteArray();

return in2b;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值