我正在尝试将数据框放入一个有两列的 Excel 工作表中,
A 列包含商店名称 B 列包含这些商店的 URL。
我想将 A 列设为可点击的超链接,这样它就不是纯文本,而是商店网站的超链接。
我尝试使用 openxlsx 包生成正确的输出。
我尝试使用以下代码片段。
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)
Run Code Online (Sandbox Code Playgroud)
这来自这篇类似性质的文章。 /sf/answers/3428142861/
然而,我的问题是当我替换代码的适当部分时,例如:
x <- df$b
names(x) <- df$a
class(x) <- "hyperlink"
writeData(wb, sheet = 1, x = x, startCol = 10)
Run Code Online (Sandbox Code Playgroud)
它没有给我一列以商店名称作为输出的超链接,而是给我整个 URL 作为输出。我的代码中是否缺少某些内容?
我得到一个包含可点击链接的输出,但它没有与名称一起显示 URL,而是仅打印出 URL。
使用的方法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)
Run Code Online (Sandbox Code Playgroud)