You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用openxlsx调整Excel中插入图片的精确位置?

实现Excel中图片的精确绝对位置插入(替代openxlsx方案)

openxlsx的insertImage函数仅支持通过行列定位图片,没法直接设置绝对英寸坐标。想要实现精确的左上角位置(左侧13.64英寸、顶部0.74英寸),可以用officer包完成,这个包对Excel布局的控制更灵活。

具体代码示例

# 安装并加载officer包
if (!require(officer)) install.packages("officer")
library(officer)

# 加载目标Excel模板
wb <- read_xlsx(path = "Templates/CB.xlsx")

# 获取第一个工作表对象
target_sheet <- wb$sheets[[1]]

# 插入图片,指定绝对位置和尺寸
target_sheet <- target_sheet %>%
  ph_with_img(
    src = "tm_player_image.png",
    left = inches(13.64),
    top = inches(0.74),
    width = inches(1.1),
    height = inches(1.73)
  )

# 替换原工作表并保存文件
wb$sheets[[1]] <- target_sheet
print(wb, target = "createWorkbookExample.xlsx")

补充说明

  • inches()是officer内置函数,用来将英寸值转换为Excel内部识别的单位,确保位置精度。
  • 如果一定要用openxlsx,只能先手动调整目标位置对应单元格的行高、列宽,反向计算出startRow和startCol,但这种方法受单元格尺寸限制,精度很难保证,远不如officer的绝对定位直接可靠。

内容的提问来源于stack exchange,提问作者Ekrem Bayar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 19:55:18