As described in other answers, the error occurs for .xlsx
files opened in Excel and synced with OneDrive/Sharpoint/Teams. The easy solution to read in the file is to close Excel and re-run readxl::read_excel()
again.
However, sometimes it would be more convenient to keep it open and still be able to read it into R. This StackOverflow answer suggests to make a temporary copy. However, it uses file.copy()
command which (at least for me) also does not work for open excel files.
The only solution which worked for me (on Windows) was to create a temporary copy of the file using the PowerShell command Copy-Item
. See the function below:
read_excel_tmp <- function(path, sheet = NULL, range = NULL, col_names = TRUE,
col_types = NULL, na = "", trim_ws = TRUE,
skip = 0, n_max = Inf, guess_max = min(1000, n_max),
progress = readxl::readxl_progress(),
.name_repair = "unique"){
destfile <- tempfile(fileext = ".xlsx")
mycmd <- paste0("powershell -command \"Copy-Item '", gsub("/", "\\\\", path),
"' -Destination '", destfile, "'\"")
error_code <- system(mycmd)
if(error_code != 0) {stop("Powershell's `Copy-Item` was not able to copy-paste the file")}
readxl::read_excel(path = destfile, sheet = sheet, range = range,
col_names = col_names, col_types = col_types, na = na,
trim_ws = trim_ws, skip = skip, n_max = n_max,
guess_max = guess_max, progress = progress,
.name_repair = .name_repair)
}
After you defined the function, the command below should also work for excel files which are currently opened
city_codes <- read_excel_tmp("./data/file.xlsx", sheet = "city_codes")
(Note: only works on Windows)