使用POI在Excel里插入图片,如何使插入的图片使用固定的大小?先介绍原有的两种方式:

  一种是指定开始和结尾单元格,然后从头画到尾,相当于平铺
  还有一种就是仅指定开始的单元格,图片的大小跟这个单元格的长宽有关,可以放大缩小固定的倍数,相当于左对齐

第一种效果如下:

第二种效果如下:

第一种方法的关键代码如下:

  1. private void pictureToSheet(Sheet finalSheet, Row row, Cell cell, int pictureIdx) {
  2. Drawing patriarch = finalSheet.createDrawingPatriarch();
  3. ExcelPositionRange excelPositionRange = ExcelTransferUtils.getMergedRegionPositionRange(finalSheet, row.getRowNum(), cell.getColumnIndex());
  4. ClientAnchor anchor = patriarch.createAnchor(0, 0, 1023, 255,
  5. excelPositionRange.getFirstCol(),
  6. excelPositionRange.getFirstRow(),
  7. excelPositionRange.getLastCol(),
  8. excelPositionRange.getLastRow()
  9. );
  10. patriarch.createPicture(anchor, pictureIdx);
  11. }

注:代码中的excelPositionRange,是俺自定义的一个类型。里边只有四个变量和get/set方法,四个变量分别是单元格的开始、结尾单元格的横纵坐标。这个大家可以根据需要来改。

PS:其中1023和255指的是每个单元格被切分的份数,指定的是最后的单元格的最右下角的一个点,其方法的源代码在本文最后的附录里。

第二种方法的关键代码如下:

  1. private void pictureToSheet(Sheet finalSheet, Row row, Cell cell, int pictureIdx) {
  2. Drawing patriarch = finalSheet.createDrawingPatriarch();
  3. ExcelPositionRange excelPositionRange = ExcelTransferUtils.getMergedRegionPositionRange(finalSheet, row.getRowNum(), cell.getColumnIndex());
  4.  
  5. CreationHelper helper = finalSheet.getWorkbook().getCreationHelper();
  6. ClientAnchor anchor = helper.createClientAnchor();
  7.  
  8. // 图片插入坐标
  9. anchor.setCol1(excelPositionRange.getFirstCol());
  10. anchor.setRow1(excelPositionRange.getFirstRow());
  11.  
  12. // 使用固定的长宽比例系数
  13. double a = 5.9;
  14. double b = 1;
  15.  
  16. // 插入图片
  17. Picture pict = patriarch.createPicture(anchor, pictureIdx);
  18. pict.resize(a,b);
  19. }

进阶方法:
  在第二种方法的基础上,可以计算出不同的系数,达到生成图片都是同一个长宽的功能,从而输出固定大小的图片

  1. private void pictureToSheet(Sheet finalSheet, Row row, Cell cell, int pictureIdx) {
  2. Drawing patriarch = finalSheet.createDrawingPatriarch();
  3. ExcelPositionRange excelPositionRange = ExcelTransferUtils.getMergedRegionPositionRange(finalSheet, row.getRowNum(), cell.getColumnIndex());
  4.  
  5. CreationHelper helper = finalSheet.getWorkbook().getCreationHelper();
  6. ClientAnchor anchor = helper.createClientAnchor();
  7.  
  8. // 图片插入坐标
  9. anchor.setCol1(excelPositionRange.getFirstCol());
  10. anchor.setRow1(excelPositionRange.getFirstRow());
  11.  
  12. // 指定我想要的长宽
  13. double standardWidth = 112;
  14. double standardHeight = 41;
  15.  
  16. // 计算单元格的长宽
  17. double cellWidth = finalSheet.getColumnWidthInPixels(cell.getColumnIndex());
  18. double cellHeight = cell.getRow().getHeightInPoints()/72*96;
  19.  
  20. // 计算需要的长宽比例的系数
  21. double a = standardWidth / cellWidth;
  22. double b = standardHeight / cellHeight;
  23.  
  24. // 插入图片
  25. Picture pict = patriarch.createPicture(anchor, pictureIdx);
  26. pict.resize(a,b);
  27. }

PS:这里参考了POI获取单元格长宽的的方法:http://www.cnblogs.com/acm-bingzi/p/poiWidth.html

附录一
  一般插入图片的样例代码:

  1. // 插入 PNG 图片至 Excel
  2. String fileName = strAppRootPath + "images/" + "bxlogo.png";
  3.  
  4. InputStream is = new FileInputStream(fileName);
  5. byte[] bytes = IOUtils.toByteArray(is);
  6.  
  7. int pictureIdx = workbook.addPicture(bytes, Workbook.PICTURE_TYPE_PNG);
  8.  
  9. CreationHelper helper = workbook.getCreationHelper();
  10. Drawing drawing = sheet.createDrawingPatriarch();
  11. ClientAnchor anchor = helper.createClientAnchor();
  12.  
  13. // 图片插入坐标
  14. anchor.setCol1(0);
  15. anchor.setRow1(1);
  16. // 插入图片
  17. Picture pict = drawing.createPicture(anchor, pictureIdx);
  18. pict.resize();

附录二
  patriarch.createAnchor的源代码跟踪

  1. /**
  2. * Creates a new client anchor and sets the top-left and bottom-right
  3. * coordinates of the anchor.
  4. *
  5. * Note: Microsoft Excel seems to sometimes disallow
  6. * higher y1 than y2 or higher x1 than x2, you might need to
  7. * reverse them and draw shapes vertically or horizontally flipped!
  8. *
  9. * @param dx1 the x coordinate within the first cell.
  10. * @param dy1 the y coordinate within the first cell.
  11. * @param dx2 the x coordinate within the second cell.
  12. * @param dy2 the y coordinate within the second cell.
  13. * @param col1 the column (0 based) of the first cell.
  14. * @param row1 the row (0 based) of the first cell.
  15. * @param col2 the column (0 based) of the second cell.
  16. * @param row2 the row (0 based) of the second cell.
  17. */
  18. public HSSFClientAnchor(int dx1, int dy1, int dx2, int dy2, short col1, int row1, short col2, int row2) {
  19. super(dx1, dy1, dx2, dy2);
  20.  
  21. checkRange(dx1, 0, 1023, "dx1");
  22. checkRange(dx2, 0, 1023, "dx2");
  23. checkRange(dy1, 0, 255, "dy1");
  24. checkRange(dy2, 0, 255, "dy2");
  25. checkRange(col1, 0, MAX_COL, "col1");
  26. checkRange(col2, 0, MAX_COL, "col2");
  27. checkRange(row1, 0, MAX_ROW, "row1");
  28. checkRange(row2, 0, MAX_ROW, "row2");
  29.  
  30. setCol1((short) Math.min(col1, col2));
  31. setCol2((short) Math.max(col1, col2));
  32. setRow1(Math.min(row1, row2));
  33. setRow2(Math.max(row1, row2));
  34.  
  35. if (col1 > col2){
  36. _isHorizontallyFlipped = true;
  37. }
  38. if (row1 > row2){
  39. _isVerticallyFlipped = true;
  40. }
  41. }

  原创文章,欢迎转载,转载请注明出处!

POI插入图片至Excel使用固定的长宽的更多相关文章

  1. Python多线程Threading爬取图片,保存本地,openpyxl批量插入图片到Excel表中

    之前用过openpyxl库保存数据到Excel文件写入不了,换用xlsxwriter 批量插入图片到Excel表中 1 import os 2 import requests 3 import re ...

  2. poi将图片导入excel(Java代码)

    package com.fh.util;import java.awt.image.BufferedImage;  import java.io.ByteArrayOutputStream;  imp ...

  3. EPPlus批量插入图片到Excel

    #region 测试EPPlus插入图片        public static void Createsheel2()        {                      WebClien ...

  4. Poi 写入图片进入excel

    public static void cacheWritePicture(BufferedImage bufferImg, Sheet sheet, Workbook wb, int width, i ...

  5. NPOI插入图片到excel指定单元格

    先看效果图 下载NPOI组件(2.0以上支持.xlsx和.xls的excel,2.0以下只支持.xls) NPOI下载官网http://npoi.codeplex.com 下载解压,里面有个dotne ...

  6. python 向excel 插入图片

    这是工作中一个真实的需求. 要做gt excel 表,表中要插入图片. 1.要把图片resize 基本相同的大小. 2.通过一下脚本插入图片到excel #!/usr/bin/env python3 ...

  7. 【VBA】批量插入图片

    解决如下问题: 需要批量导入图片到Excel 图片放在一个文件夹中 图片有严格的顺序关系,即按照:共通名_编号的方式命名. 图片格式统一,即均为同一格式. 有两种方式可以插入图片到Excel中,其一为 ...

  8. Oracle数据库插入图片和读取图片

    package com.basicSql.scroll_page; import java.io.File; import java.io.FileInputStream; import java.i ...

  9. java POI实现向Excel中插入图片

          做Web开发免不了要与Excel打交道.今天老大给我一个任务-导出Excel.开始想的还是蛮简单的,无非就是查找,构建Excel,response下载即可.但是有一点不同,就是要加入图片, ...

随机推荐

  1. 9-51单片机ESP8266学习-AT指令(单片机采集温湿度数据通过8266发送给AndroidTCP客户端显示)

    http://www.cnblogs.com/yangfengwu/p/8798512.html 补充:今天答应了一个朋友写一下如果单片机发过的是字符串应该怎么解析,答应了今天写,哦哦哦是明天了,闲话 ...

  2. linux下文件共享的几种常用方式

    1. python方式,做一个简单的服务器.默认是开启8000端口. > python -m SimpleHTTPServer 执行命令后,在浏览器上输入该机器IP+8000端口即可 2. sc ...

  3. 基于uFUN开发板的RGB调色板

    前言 使用uFUN开发板配合Qt上位机,实现任意颜色的混合,Qt上位机下发RGB数值,范围0-255,uFUN开发板进行解析,然后输出不同占空比的PWM,从而实现通过RGB三原色调制出任意颜色. Qt ...

  4. Python-集合-17

    ''' 集合:可变的数据类型,他里面的元素必须是不可变的数据类型,无序,不重复. {} ''' set1 = set({1,2,3}) # set2 = {1,2,3,[2,3],{'name':'a ...

  5. Pairproject 移山之道 阅读随笔和一些问题

    首先不得不承认这本书的写作方式很独特,不像其他的计算机类的图书那样枯燥,让人读起来感觉很有意思,他也颠覆了我对计算机类图书的看法,这种写作方式值得我们学习. 先谈谈收获吧.读了两年大学,这是第一次写类 ...

  6. Android之JSON格式数据解析

    查看原文:http://blog.csdn.net/hantangsongming/article/details/42234293 JSON:JavaScript 对象表示法(JavaScript ...

  7. 使用代理创建连接池 proxyPool

    配置文件properties url=jdbc:mysql://127.0.0.1:3306/mine?characterEncoding=UTF-8 user=root password=1234 ...

  8. 第三个Sprint冲刺总结

    第三个Sprint冲刺总结 1.燃尽图 2.本阶段总结: 本阶段主要是对产品进行完善和美化,所以工作量不是很多.但要做精,做好并非是一件简单的事情.我们各组员都安排了各自的任务,如参考各行业的优秀ap ...

  9. Beta 总结

    前言 作业发布 组长 成员 贡献分 ★ 530 雨勤 14 311 旭 15 403 俊 16 223 元 14 437 海辉 17 7天 Beta 冲刺站立会议博客链接汇总 Beta 冲刺 (1/7 ...

  10. Gradle下载类库源码

    https://blog.csdn.net/xiaoxing598/article/details/68958383 备选:https://www.cnblogs.com/yoyotl/p/62917 ...