【问题标题】:Extract Links from Excel Sheet using R-package 'openxlsx'使用 R-package 'openxlsx' 从 Excel 表中提取链接
【发布时间】:2018-11-05 02:28:11
【问题描述】:

我正在使用 Excel 工作表,其中某些列包含超链接,这些超链接表示为与超链接指向的实际地址完全不同的文本。我想使用一些 R 代码来修改和子集 Excel 工作表,但保留超链接。我想我可以通过将这些超链接提取为索引字符向量然后使用makeHyperlinkString()writeFormula() 函数将它们重新引入新的 Excel 文档来做到这一点。但我无法弄清楚如何获取链接本身的向量。

如果它很重要,我的意图是对 Excel 工作表的 data.frame 版本而不是工作簿对象进行所有修改和子集。

【问题讨论】:

  • 使用openxlsx,您应该能够使用loadWorkbook 并使用writeData 写入特定的工作表/单元格,然后使用saveWorkbook 而不会更改任何其他单元格/工作表。

标签: r excel hyperlink openxlsx


【解决方案1】:

哦,现在我想我遇到了你的问题。我以为只有普通的超链接而不是 Excel 超链接。

我认为这可能会帮助您获得超链接的矢量,尽管它有点混乱。

library(openxlsx)
pathtofile =  "path to .xlsx file"

df1 <- read.xlsx(xlsxFile = pathtofile, 
                 sheet = 1, skipEmptyRows = FALSE, 
                 colNames = F, rowNames = F,
                startRow = 1)

## Sheet or Tabelle
Sheet = "Sheet" ## Or "Tabelle"

## Get Names of rows from Hyperlink column
rowIndex <- sub(x = df1[,1], pattern = paste0("(#'",Sheet,"\\d'!)"), replacement = "")

## Get the Sheet, where Hyperlinks are saved
SheetName <- regmatches(df1[,1], regexpr(text = df1[,1], pattern = paste0("(",Sheet,"\\d)")))
## Extract only the Sheet number
SheetIndex <- as.numeric(sub(x = SheetName, pattern = Sheet, replacement = ""))

## Get the row Indexes as numeric
RowIndexNum <- as.numeric(regmatches(rowIndex, regexpr(text = rowIndex, pattern = "\\d")))
## Get the column name as character
RowIndexName <- sub(x = rowIndex, pattern = "\\d", "")
## Create uppercase Letters
myLetters <- toupper(letters[1:26])
## Convert Row Name (character) to numeric (based on alphabetical order)
RowIndexNameNum <- match(RowIndexName, myLetters)

## If Hyperlinks only in 1 Sheet or several sheets
if (length(unique(SheetIndex)) == 1) {
  dfLinks <- read.xlsx(xlsxFile = pathtofile,
                       sheet = unique(SheetIndex), 
                       skipEmptyRows = FALSE, 
                       colNames = F, rowNames = F, 
                       rows = RowIndexNum[1]:tail(RowIndexNum,1),
                       cols = unique(RowIndexNameNum),
                       startRow = 1
                       );
} else {
  dfLinks <- data.frame()
  for (i in unique(SheetIndex)){
    dfTmp <- read.xlsx(xlsxFile = pathtofile,
              sheet = i, 
              skipEmptyRows = FALSE, 
              colNames = F, rowNames = F, 
              rows = RowIndexNum[1]:tail(RowIndexNum,1),
              cols = unique(RowIndexNameNum),
              startRow = 1)
    dfLinks <- rbind(dfLinks, dfTmp)
  }
}

dfLinks

这是我的 Excel 文件的样子:

【讨论】:

  • 不,当我这样做时,data.frame 包含显示文本而不是链接指向的地址。
  • 我编辑了我的答案,因为我认为我误解了这个问题。也许我仍然这样做.. :)
猜你喜欢
  • 1970-01-01
  • 2021-02-01
  • 1970-01-01
  • 2011-04-14
  • 1970-01-01
  • 2016-08-26
  • 1970-01-01
  • 2021-10-23
  • 2018-02-16
相关资源
最近更新 更多