I am working with R (shiny) and want to save a dataframe as an excel file. For this purpose I use the "shinyFiles" package so that the user can specify where the excel file is to be stored:
server.R library(shiny) library(shinyFiles)
shinyServer(function(input, output, session) {
## ShinyFiles : get the user favorite directory
volumes=c(home = '~/'),
shinyDirChoose(input, 'dir', roots=volumes, filetypes = c('','xlsx')),
output$dir.res <- renderPrint({parseDirPath(volumes, input$dir)}),
## Button to save the file
observeEvent(input$button.save, {
## A standard file name
A <- "name"
B <- "family
if( input$text == "File name..." ) outFile <- paste( A, "_", B, ".xlsx", sep="" )
## Append the path to the file name
outFile <- paste( parseDirPath(volumes, input$path.out), outFile, sep="/" )
## The data to be saved
x=seq(from=0,to=10,by=1)
d = data.frame( x )
write.xlsx( d, outFile )
}
and the ui.R
library(shiny)
library(shinyFiles)
shinyUI(fluidPage(sidebarLayout(
## Choose the output directory
shinyDirButton("dir", "Choose directory", "Upload"),
## Choose the output file name
textInput("text", label = "", value = "File name..."),
## Save the data
actionButton("button.save", "Save the file"),
## Give the path selected
verbatimTextOutput("dir.res")
)))
Despite all the examples found for similar questions I have been trying around for 2h (shame..) and will be thankful for help
Here is a working example. Again, this assumes that you run the app on your own computer, and users are allowed to access folders on this computer. You can set the root folder where user is allowed to save files (see UserFolder
, user will be able to choose any subfolder of this root)
library(shiny)
library(shinyFiles)
library(xlsx)
ui <- shinyUI(fluidPage(
titlePanel("Example"),
shinySaveButton("save", "Save file", "Save file as ...", filetype=list(xlsx="xlsx"))
))
server <- shinyServer(function(input, output, session) {
observe({
volumes <- c("UserFolder"="D:/Data")
shinyFileSave(input, "save", roots=volumes, session=session)
fileinfo <- parseSavePath(volumes, input$save)
data <- data.frame(a=c(1,2))
if (nrow(fileinfo) > 0) {
write.xlsx(data, as.character(fileinfo$datapath))
}
})
})
shinyApp(ui = ui, server = server)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With