简体   繁体   中英

I am facing error in pasting an image in Excel from R using package openxlsx

I am trying to paste an image saved in my folder to Excel using R package openxlsx. I have completely studied the package documentation and followed the steps given in the documentation. But even the example given in package is not working for me

## Create a new workbook
wb <- createWorkbook("Ayanami")
## Add some worksheets
addWorksheet(wb, "Sheet 1")
addWorksheet(wb, "Sheet 2")
addWorksheet(wb, "Sheet 3")
## Insert images
img <- system.file("einstein.jpg", package = "openxlsx")
insertImage(wb, "Sheet 1", img, startRow = 5, startCol = 3, width = 6, height = 5)
insertImage(wb, 2, img, startRow = 2, startCol = 2)
insertImage(wb, 3 , img, width = 15, height = 12, startRow = 3, startCol = "G", units = "cm")
## Save workbook
saveWorkbook(wb, "insertImageExample.xlsx", overwrite = TRUE)

This is the example given in package documentation. Instead of "einstein.jpg", I am using my ".jpg" file. I am trying to paste that image in my workbook 'wb'. The function "system.file" does not fetch the image I am passing. I have made sure that there is no issues related to path whether image has been stored.

Could anyone of help me with this function or has any verified alternative?

You shouldn't use system.file function as the image that you are trying to paste in the workbook isn't a system file.

instead you will need something like:

img <- "C:/your_dir/your_filename.jpg"

insertImage(wb, "Sheet 1", img, startRow = 5, startCol = 3, width = 6, height = 5)
saveWorkbook(wb, "insertImageExample2.xlsx", overwrite = TRUE)

For context, you are likely stepping through the documentation for openxlsx here: ycphs.github.io/openxlsx/articles/Introduction.html

The link to the image is incorrect on the link. You should use:

img <- readJPEG(file.path(path.package("openxlsx"), "extdata/einstein.jpg"))

Try something like this:

    library(jpeg)
    img<-readJPEG("einstein.jpg")
    plotFn(img)
    insertPlot(wb, 1)
    saveWorkbook(wb, "insertImageExample.xlsx", overwrite = TRUE)
    file.show("insertImageExample.xlsx")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM