List and download files from Sharepoint site in r

Once connected to my sharepoint site, I use list_items and get a data frame of the file names in my folder. How do I upload/download all files at once to my working directory so I can then combine the files and clean?

Hi @mme333, I think you're using Microsoft365R package to interface with SharePoint, is that right?

It seems you already have this, but for clarity here is how I got a reference to a SharePoint folder containing data I'm interested in downloading using the Microsoft365R package:

# libraries
library(Microsoft365R)    # interfaces with SharePoint
library(tidyverse)        # data wrangling
library(purrr)            # iteratively apply functions
library(here)             # localised file and folder references

# get a reference to a sharepoint data folder using Microsoft365R functions
team <- get_team(team_name = 'My Team')
channel <- team$get_channel(channel_name = 'My Channel')
folder <- channel$get_folder()
data_folder <- folder$get_item('Top folder/Data folder/') 

data_folder is a Microsoft365R object which references the SharePoint folder containing all the files I wish to download. list_items() lists the names of files in this folder (excluding sub-directories) in a data.frame, saved here as files:

files <- data_folder$list_items() |> filter(!isdir)

NB, files is a data.frame of 4 variables:

  • name - the name of the file, including extension

  • size - the size of the file, in bytes

  • isdir - boolean indicating if the item is a subdirectory

  • id - a unique id for the file

Iterate over the name of each file in files and download to a folder called data in the current working directory using an anonymous function:

purrr::walk(
  .x = files$name,
  \(.filename) {
    # get a reference to the document
    doc <- data_folder$get_item(.filename)
    # download it to a folder called 'data' within the working directory
    doc$download(dest = here('data', .filename), overwrite = T)
  }
)
1 Like