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

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

第一种效果如下:

第二种效果如下:

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

 private void pictureToSheet(Sheet finalSheet, Row row, Cell cell, int pictureIdx) {
Drawing patriarch = finalSheet.createDrawingPatriarch();
ExcelPositionRange excelPositionRange = ExcelTransferUtils.getMergedRegionPositionRange(finalSheet, row.getRowNum(), cell.getColumnIndex());
ClientAnchor anchor = patriarch.createAnchor(0, 0, 1023, 255,
excelPositionRange.getFirstCol(),
excelPositionRange.getFirstRow(),
excelPositionRange.getLastCol(),
excelPositionRange.getLastRow()
);
patriarch.createPicture(anchor, pictureIdx);
}

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

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

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

 private void pictureToSheet(Sheet finalSheet, Row row, Cell cell, int pictureIdx) {
Drawing patriarch = finalSheet.createDrawingPatriarch();
ExcelPositionRange excelPositionRange = ExcelTransferUtils.getMergedRegionPositionRange(finalSheet, row.getRowNum(), cell.getColumnIndex()); CreationHelper helper = finalSheet.getWorkbook().getCreationHelper();
ClientAnchor anchor = helper.createClientAnchor(); // 图片插入坐标
anchor.setCol1(excelPositionRange.getFirstCol());
anchor.setRow1(excelPositionRange.getFirstRow()); // 使用固定的长宽比例系数
double a = 5.9;
double b = 1; // 插入图片
Picture pict = patriarch.createPicture(anchor, pictureIdx);
pict.resize(a,b);
}

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

 private void pictureToSheet(Sheet finalSheet, Row row, Cell cell, int pictureIdx) {
Drawing patriarch = finalSheet.createDrawingPatriarch();
ExcelPositionRange excelPositionRange = ExcelTransferUtils.getMergedRegionPositionRange(finalSheet, row.getRowNum(), cell.getColumnIndex()); CreationHelper helper = finalSheet.getWorkbook().getCreationHelper();
ClientAnchor anchor = helper.createClientAnchor(); // 图片插入坐标
anchor.setCol1(excelPositionRange.getFirstCol());
anchor.setRow1(excelPositionRange.getFirstRow()); // 指定我想要的长宽
double standardWidth = 112;
double standardHeight = 41; // 计算单元格的长宽
double cellWidth = finalSheet.getColumnWidthInPixels(cell.getColumnIndex());
double cellHeight = cell.getRow().getHeightInPoints()/72*96; // 计算需要的长宽比例的系数
double a = standardWidth / cellWidth;
double b = standardHeight / cellHeight; // 插入图片
Picture pict = patriarch.createPicture(anchor, pictureIdx);
pict.resize(a,b);
}

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

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

 // 插入 PNG 图片至 Excel
String fileName = strAppRootPath + "images/" + "bxlogo.png"; InputStream is = new FileInputStream(fileName);
byte[] bytes = IOUtils.toByteArray(is); int pictureIdx = workbook.addPicture(bytes, Workbook.PICTURE_TYPE_PNG); CreationHelper helper = workbook.getCreationHelper();
Drawing drawing = sheet.createDrawingPatriarch();
ClientAnchor anchor = helper.createClientAnchor(); // 图片插入坐标
anchor.setCol1(0);
anchor.setRow1(1);
// 插入图片
Picture pict = drawing.createPicture(anchor, pictureIdx);
pict.resize();

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

 /**
* Creates a new client anchor and sets the top-left and bottom-right
* coordinates of the anchor.
*
* Note: Microsoft Excel seems to sometimes disallow
* higher y1 than y2 or higher x1 than x2, you might need to
* reverse them and draw shapes vertically or horizontally flipped!
*
* @param dx1 the x coordinate within the first cell.
* @param dy1 the y coordinate within the first cell.
* @param dx2 the x coordinate within the second cell.
* @param dy2 the y coordinate within the second cell.
* @param col1 the column (0 based) of the first cell.
* @param row1 the row (0 based) of the first cell.
* @param col2 the column (0 based) of the second cell.
* @param row2 the row (0 based) of the second cell.
*/
public HSSFClientAnchor(int dx1, int dy1, int dx2, int dy2, short col1, int row1, short col2, int row2) {
super(dx1, dy1, dx2, dy2); checkRange(dx1, 0, 1023, "dx1");
checkRange(dx2, 0, 1023, "dx2");
checkRange(dy1, 0, 255, "dy1");
checkRange(dy2, 0, 255, "dy2");
checkRange(col1, 0, MAX_COL, "col1");
checkRange(col2, 0, MAX_COL, "col2");
checkRange(row1, 0, MAX_ROW, "row1");
checkRange(row2, 0, MAX_ROW, "row2"); setCol1((short) Math.min(col1, col2));
setCol2((short) Math.max(col1, col2));
setRow1(Math.min(row1, row2));
setRow2(Math.max(row1, row2)); if (col1 > col2){
_isHorizontallyFlipped = true;
}
if (row1 > row2){
_isVerticallyFlipped = true;
}
}

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

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. C# 邮箱的使用

    using System; using System.Collections.Generic; using System.ComponentModel; using System.Configurat ...

  2. RocketMQ环境搭建

    1 源码下载 wget http://mirror.bit.edu.cn/apache/rocketmq/4.2.0/rocketmq-all-4.2.0-bin-release.zip unzip ...

  3. 用JavaDoc生成项目文档

    项目到了尾声,大家都开始头疼——又要写文档了……是的,我们大多数人都不是从正规的Programer训练出来的.当初学习编程序的时候,就从来没有想过要给自己写的那几个程序编写一份完整的文档,所有的注释都 ...

  4. Spring Boot Admin 日志查看功能

    按照官方配置POM和配置文件后,能够结合Eureka查看各微服务状态,但是日志始终查看不了,出现406等错误. 最后偶然发现,是在在从官方网站拷贝配置的时候,出现的问题. logging.file=* ...

  5. CSV文件解析

    CSV(逗号分隔值文件格式)        逗号分隔值(Comma-Separated Values,CSV,有时也称为字符分隔值,因为分隔字符也可以不是逗号),其文件以纯文本形式存储表格数据(数字和 ...

  6. mybatis 反射bean规则

    1,根据查询字段名,寻找 bean变量名设置,变量可为私有属性 2,根据查询字段名 set方法名,设置bean属性 此方法 为 ‘set‘+字段名,大小写忽略,即 方法set后面第一个字母可以是大小写 ...

  7. EZ 2018 07 06 NOIP模拟赛

    又是慈溪那边给的题目,这次终于没有像上次那样尴尬了, T1拿到了较高的暴力分,T2没写炸,然后T3写了一个优雅的暴力就203pts,Rank3了. 听说其它学校的分数普遍100+,那我们学校还不是强到 ...

  8. 深入理解USB流量数据包的抓取与分析

    0x01 问题提出 在一次演练中,我们通过wireshark抓取了一个如下的数据包,我们如何对其进行分析? 0x02 问题分析 流量包是如何捕获的? 首先我们从上面的数据包分析可以知道,这是个USB的 ...

  9. Tomcat利用MSM实现Session共享方案解说

    Session共享有多种解决方法,常用的有四种:1)客户端Cookie保存2)服务器间Session同步3)使用集群管理Session(如MSM) 4)把Session持久化到数据库 针对上面Sess ...

  10. 这是一个数学题牛客训练赛E

    题目描述   https://www.nowcoder.net/acm/contest/78/E 已知有一个n+1个数的数列,对于给定的A0和An ,当i满足当1<=i<=n-1时有    ...