【问题标题】:Openxlsx hyperlink output display in ExcelExcel中的Openxlsx超链接输出显示
【发布时间】:2020-05-23 17:01:18
【问题描述】:

我正在尝试在一个数据框中输入一个有两列的 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)

来自这篇类似性质的帖子。 https://stackoverflow.com/a/48973469/11958444

然而,我的问题是当我替换代码的适当部分时,例如:

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

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

它没有给我一列以商店名称作为输出的超链接,而是给我整个 URL 作为输出。我的代码中是否缺少某些内容?

我得到一个带有可点击链接的输出,但它没有显示 URL 的名称,而是打印出 URL。

【问题讨论】:

  • 为了让这个可以重现,你能把df的一部分分享给head(dput(df))吗?
  • 是的,我会给你一个reprex。我需要制作数据集。出于示例的目的,我更改了我的数据。我会制作一个虚拟套装并给你一个reprex。

标签: r excel openxlsx


【解决方案1】:

一种使用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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-04
    • 1970-01-01
    • 2013-09-14
    • 1970-01-01
    • 2016-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多