0

I'm having trouble with the insertImage function in R package openxlsx. Every time I insert a new image, all the other images in the document collapse and don't show. Any ideas?

OTStats
  • 1,820
  • 1
  • 13
  • 22
  • Can you please provide a code example of what you have tried? – John Carty Dec 02 '19 at 14:35
  • I have tried with `insertImage("01", img1, width = 13, height = 8.5, startRow = 11, startCol = 2, units = "cm", dpi = 96)`. This is all part of a 96 line code written to iterate a excel template over several hundreds of rows of information – Martín Rosas Araya Dec 02 '19 at 15:41

2 Answers2

0

Without seeing more of your code I am not sure I can be of much help. I was able to use your snippet to insert two images without issue (one below the other). Here is a link to the insertImage() documentation.

library(openxlsx)

wb <- openxlsx::loadWorkbook("M:\\imageTest.xlsx")
wb %>% 
  insertImage("01", "C:\\Users\\jcarty\\Desktop\\imageTest.jpg", width = 13, height = 8.5
              , startRow = 11, startCol = 2, units = "cm", dpi = 96) 
wb %>% 
  saveWorkbook("M:\\imageTest.xlsx", overwrite = TRUE)


wb <- openxlsx::loadWorkbook("M:\\imageTest.xlsx")
wb %>% 
  insertImage("01", "C:\\Users\\jcarty\\Desktop\\imageTest2.jpg", width = 13, height = 8.5
              , startRow = 27, startCol = 2, units = "cm", dpi = 96) 
wb %>% 
  saveWorkbook("M:\\imageTest.xlsx", overwrite = TRUE)

John Carty
  • 242
  • 2
  • 13
0

I have the same problem whenever I try to insert more than 2 images in the same sheet. Apparently, this is a know issue in the package: https://github.com/awalker89/openxlsx/issues/373.

It's not much of a solution, but the only thing you can do is insert the images into separate sheets, and then manually combine the sheets if desired.

If you define a figure number, you can do something like this:

fignum <- 1

# Set current sheet name
# For uneven figure numbers
if ((fignum %% 2) != 0) {
  
  # Set plot name to current number
  current_sheetname <- paste0("plot_", fignum)
  
# For even figure numbers
} else {
  
  # Set plot name to previous number
  current_sheetname <- paste0("plot_", fignum - 1)
}

# Check if the current worksheet name doesn't exist yet
if (!(current_sheetname %in% names(wb))) {
  # Create new worksheet
  openxlsx::addWorksheet(wb = wb,
                         sheetName = current_sheetname)
}

# Write figure to new worksheet
openxlsx::insertImage(wb = wb,
                      sheet = current_sheetname,
                      file = img1)