下载googlesheet并在特定路径中创建文件夹以保存

download googlesheet and create folder in specific path to save

我在下面提到了下载 google sheet 并将其存储在 Documents 中的代码。

library(dplyr)
library(data.table)
library(googlesheets)
library(rJava)

t.start<-Sys.Date()
t.start<-as.character(t.start)

#gs_auth(new_user = TRUE) 
#gs_ls()
#gs_auth()
as<-gs_title("XYZ")
gs_download(as, overwrite = TRUE)

我希望 sheet XYZ 存储到具有以下条件的特定位置(即 E:\My_data\File)。

您可以使用以下代码来执行此操作:

# To handle the googlesheets
require(googlesheets)

# For easier date manipulation
require(lubridate)

# Get current time
t <- Sys.time()

# Set your base path and create the basic file structure
base_path <- "E:/My_data/File"
dir.create(paste0(base_path, year(t)))
sub_folder_path <- paste0(base_path, year(t), "/", month(t, label = TRUE), "-", day(t))
dir.create(sub_folder_path)

AB_split <- ifelse(hour(t)<15, "A", "B")
dir.create(paste0(sub_folder_path, "/", AB_split))

# Set your gsheet title and the wanted file-name
ws_title <- "XYZ"
ws_file_name <- paste0(date(t), "_", AB_split, "_", ws_title, ".xlsx")
ws_file_path <- paste0(sub_folder_path, "/", AB_split, "/", ws_file_name)

# Download it
as<-gs_title(ws_title)
gs_download(as, to = ws_file_path, overwrite = TRUE)

如果出现警告,则尝试创建现有文件夹。如果您想抑制警告,请将 create.dir 调用包装在 suppressWarnings(create.dir(...))

我强烈建议 不要 使用工作表标题,而是使用键。参见 ?gs_key