【问题标题】:Make all row-entries in a column hyperlinks (Excel file production in R)在列超链接中创建所有行条目(R 中的 Excel 文件生成)
【发布时间】:2015-10-07 09:09:05
【问题描述】:

不幸的是,许多人使用 Excel 并导出到 xlsx 很重要。 我想生成带有超链接的“用户友好的数据输出”。

如何在 R 中生成具有 2 列的 excel 文件,其中第一列将是超链接(所需的链接在第三列中指定)。 (这都是关于演示数据的)

(在我读取的数据集和输出文件中,我需要大约 10 个这样的列“超链接增强”)。 一定是极品! HTML不会削减它! (数据集是 20k 行,浏览器会冻结和滚动,列冻结很重要)

在此处查看示例数据:

library(dplyr)
df<-select(iris,Species,Sepal.Length)
library(stringr)
df$hyperlink <-str_c('http://species.org/',df$Species)

> df[49:54,]
      Species Sepal.Length                     hyperlink
49     setosa          5.3     http://species.org/setosa
50     setosa          5.0     http://species.org/setosa
51 versicolor          7.0 http://species.org/versicolor
52 versicolor          6.4 http://species.org/versicolor
53 versicolor          6.9 http://species.org/versicolor
54 versicolor          5.5 http://species.org/versicolor

编辑: 理想情况下,该代码将允许将 data.frame 中的任何列设为由公式指定的链接(请参阅我使用函数 str_c 的代码中的公式)。假设 df 有 20 多列并再次手动组合它(最好避免使用 xlsx)。

xlxs 中的解决方案很好,但也可以选择其他包(或在 Python 中执行)。

应该是这样的:

【问题讨论】:

    标签: r excel hyperlink


    【解决方案1】:

    xlsx 包中有一个方法可以为单元格添加超链接。以下是使用 for 循环添加超链接的方法。

    如果其他人知道如何在不使用 for 循环的情况下执行此操作(即,将整个向量添加为一列单元格),效率会更高。

    library(xlsx)
    wb <- createWorkbook()
    sheet1 <- createSheet(wb, "Sheet1")
    rows <- createRow(sheet1, seq_along(df$hyperlink)) 
    cells <- createCell(rows, colIndex=1:2) # 2 columns
    for (i in seq_along(cells[,1])){
      col1 <- cells[[i,1]]
      setCellValue(col1, df$Species[i])
      addHyperlink(col1,df$hyperlink[i])
      col2 <- cells[[i,2]]
      setCellValue(col2,df$Sepal.Length[[i]])
    }
    saveWorkbook(wb, file="workbook.xlsx") # Add your file path here
    

    【讨论】:

    • 它在正确的道路上。结果应该只有 2 列。所以第一列的值应该是 setCellValue(col1,df$Species) 并且 col1 应该在第 3 列中有链接;另外, col2 应该是 Sepal.Length
    • @userJT 已编辑以反映正确的列值并添加了屏幕截图。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-22
    • 1970-01-01
    相关资源
    最近更新 更多