67,512
社区成员
发帖
与我相关
我的任务
分享
public static void main(String[] args) {
FileOutputStream fileOut = null;
try {
// 先把读进来的图片放到一个ByteArrayOutputStream中,以便产生ByteArray
ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
ImageIO.write(Test.createImage(), "jpg", byteArrayOut);
// 创建一个工作薄
HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream("d:/test.xls"));
HSSFSheet sheet1 = wb.getSheetAt(0);
HSSFPatriarch patriarch = sheet1.createDrawingPatriarch();
//HSSFClientAnchor几个数字解释:3:是x轴的开始节点, 0: 是y轴的开始节点,1023:是x轴的结束节点,255:是y轴的结束节点,1:是从Excel的2列开始插入图片,10:是从excel的第11行开始插入图片, 11:图片占用11列的位置,25:图片结束在excel的26行
HSSFClientAnchor anchor = new HSSFClientAnchor(3, 0, 1023, 255,(short) 1, 10,(short) 11, 25);
anchor.setAnchorType(2);
// 插入图片
patriarch.createPicture(anchor, wb.addPicture(byteArrayOut.toByteArray(),HSSFWorkbook.PICTURE_TYPE_JPEG));
fileOut = new FileOutputStream("d:/workbook.xls");
// 写入excel文件
wb.write(fileOut);
fileOut.close();
} catch (IOException io) {
io.printStackTrace();
System.out.println("io erorr : " + io.getMessage());
} finally {
if (fileOut != null) {
try {
fileOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static BufferedImage createImage(){
int width = 100;
int height = 100;
String s = "你好";
Font font = new Font("Serif", Font.BOLD, 10);
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = (Graphics2D)bi.getGraphics();
g2.setBackground(Color.WHITE);
g2.clearRect(0, 0, width, height);
g2.setPaint(new Color(0,0,255));
g2.fillRect(0, 0, 100, 10);
g2.setPaint(new Color(253,2,0));
g2.fillRect(0, 10, 100, 10);
g2.setPaint(Color.red);
FontRenderContext context = g2.getFontRenderContext();
Rectangle2D bounds = font.getStringBounds(s, context);
double x = (width - bounds.getWidth()) / 2;
double y = (height - bounds.getHeight()) / 2;
double ascent = -bounds.getY();
double baseY = y + ascent;
g2.drawString(s, (int)x, (int)baseY);
return bi;
}
request.getSession().getServletContext().getRealPath("")+"/image/image.png"