rexcelopenxlsx

Openxlsx hyperlink output display in Excel


I am trying to take in a data frame an excel sheet that has two columns,

Column A contains names of stores Column B contains the URL of those stores.

I would like to take Column A and make it a clickable hyperlink so instead of plain text, it is a hyperlink to the store website.

I have attempted to use openxlsx package to generate the correct output.

I have attempted to use the following code snip.

x <- c("https://www.google.com", "https://www.google.com.au")
names(x) <- c("google", "google Aus")
class(x) <- "hyperlink"

writeData(wb, sheet = 1, x = x, startCol = 10)

which comes from this post of a similar nature. https://stackoverflow.com/a/48973469/11958444

My problem however is when I replace the appropriate parts of the code e.g.:

x <- df$b
names(x) <- df$a
class(x) <- "hyperlink"

writeData(wb, sheet = 1, x = x, startCol = 10)

instead of giving me a column of hyperlinks that has the store name as the output, it gives me the entire URL as the output. Is there something I am missing from my code?

I get an output that has a clickable link, but instead of the URL appearing with the name, it instead just prints out the URL.


Solution

  • An approach using openxlsx:

    library(openxlsx)
    library(dplyr)
    
    # create sample data
    df <- data.frame(
      site_name = c("Zero Hedge", "Free Software Foundation"),
      site_url = c("https://www.zerohedge.com", "https://www.fsf.org")
    )
    
    # add new column that manually constructs Excel hyperlink formula
    # note backslash is required for quotes to appear in Excel
    df <- df %>%
      mutate(
        excel_link = paste0(
          "HYPERLINK(\"",
          site_url,
          "\", \"",
          site_name,
          "\")"
        )
      )
    
    # specify column as formula per openxlsx::writeFormula option #2
    class(df$excel_link) <- "formula"
    
    # create and write workbook
    wb <- createWorkbook()
    addWorksheet(wb, "df_sheet")
    writeData(wb, "df_sheet", df)
    saveWorkbook(wb, "wb.xlsx", overwrite = TRUE)