簡體   English   中英

在R中讀取打開的excel文件

[英]Read open excel file in R

有沒有辦法將打開的 excel 文件讀入 R?

在 Excel 中打開 excel 文件時,Excel 會對該文件進行鎖定,例如 R 中的讀取方法無法訪問該文件。

你能繞過這個鎖嗎?

謝謝

編輯:這發生在具有原始 excel 的窗口下。

您所說的“R 中的讀取方法”和“無法訪問文件”是什么意思(即您使用的是什么代碼以及您究竟得到了什么錯誤消息)? 我正在成功導入當前打開的 Excel 文件,例如:

dat <- readxl::read_excel("PATH/TO/FILE.xlsx")

如果文件正在 Excel 中編輯,R 將導入最后保存的版本。

編輯:我現在在 Linux 和 Windows 上都試過了,它仍然可以工作,至少在 1.3.1 版的“readxl”上是這樣。

我也沒有打開已經在 excel 中打開的 xlsx 文件的問題,但如果你這樣做,我有一個可能有效的解決方法:

path_to_xlsx <- "C:/Some/Path/to/test.xlsx"
temp <- tempdir()
file.copy(path_to_xlsx, to = paste0(temp, "/test.xlsx"))
df <- openxlsx::read.xlsx(paste0(temp, "/test.xlsx"))

這會將文件(不應被阻止)復制到臨時目錄,然后從那里加載文件。 同樣,我不確定這是否需要,因為我沒有您遇到的問題。

您可以使用ps包嘗試類似的操作。 我已經在 Windows 和 Mac 上使用它來讀取從某些網絡資源下載並在Excel使用openxlsx2打開的文件,但它也應該適用於其他包或程序。

# get the path to the open file via the ps package
library(ps)
p <- ps()
# get the pid for the current program, in my case Excel on Mac
ppid <- p$pid[grepl("Excel", p$name)]
# get the list of open files for that program
pfiles <- ps_open_files(ps_handle(ppid))
pfile <- pfiles[grepl(".xlsx", pfiles$path),]

# return the path to the file
sel <- grepl("^(.|[^~].*)\\.xlsx", basename(pfile$path))
path <- pfile$path[sel]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM