Openxlsx hyperlink output display in Excel

丶灬走出姿态 提交于 2020-12-13 04:06:38

问题


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.


回答1:


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)


来源:https://stackoverflow.com/questions/61975608/openxlsx-hyperlink-output-display-in-excel

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!