R使用链接写入Excel

ct2axkht  于 2023-01-03  发布在  其他
关注(0)|答案(3)|浏览(131)

我想知道如何将一个r数据框导出到excel格式的文件中,并嵌入一些链接。这样我就可以使用R创建一个xlsm文件。当打开xlsm文件时,我可以点击某些链接打开其他文件或网页。
我查了几个R“Write-to-Excel”包,几乎没有一个有这样的功能。
有人知道吗?
谢谢!

mkshixfv

mkshixfv1#

xlsx包中有addHyperlink函数,正是为了这个目的。example(addHyperlink)应该可以帮助您入门。

yacmzcpb

yacmzcpb2#

现代的方法可能是使用openxlsx包。请参阅?makeHyperlinkString的文档,如下所示:

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)
vawmfj5a

vawmfj5a3#

类似于Excel中的Openxlsx超链接输出显示......我使用openxlsx对此提出了三个解决方案

1.将url列标记为超链接

library(openxlsx)

# 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")
)

# create and write workbook
wb <- createWorkbook()
addWorksheet(wb, "df_sheet")

class(df$site_url)<-"hyperlink" # mark as a hyperlink
writeData(wb,"df_sheet",df$site_url,startCol = which(colnames(df)=="site_url"), startRow = 2)

writeData(wb, "df_sheet", df) # overwrite the sheet

saveWorkbook(wb, "wb.xlsx", overwrite = TRUE)

2.将超链接应用到site_name列

library(openxlsx)

# 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")
)

# create and write workbook
wb <- createWorkbook()
addWorksheet(wb, "df_sheet")

class(df$site_url)<-"hyperlink" # mark as a hyperlink
writeData(wb,"df_sheet",df$site_url,startCol = which(colnames(df)=="site_name"), startRow = 2)

class(df$site_url)<-"character" # change back to a character which is optional

writeData(wb, "df_sheet", df) # overwrite the sheet to get the new pretty name overlaying the hyperlink

saveWorkbook(wb, "wb.xlsx", overwrite = TRUE)

3.新列,其中的链接应用于site_name中的名称

library(openxlsx)

# 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")
)

df$pretty_link<-df$site_name #new column for pretty link

# create and write workbook
wb <- createWorkbook()
addWorksheet(wb, "df_sheet")

class(df$site_url)<-"hyperlink" # mark as a hyperlink
writeData(wb,"df_sheet",df$site_url,startCol = which(colnames(df)=="pretty_link"), startRow = 2)

class(df$site_url)<-"character" # change back to a character which is optional

writeData(wb, "df_sheet", df) # overwrite the sheet to get the new pretty name overlaying the hyperlink

saveWorkbook(wb, "wb.xlsx", overwrite = TRUE)

相关问题