2016-09-15 143 views
2

我正在使用R(有光澤)並希望將數據框保存爲excel文件。 爲此我使用了「shinyFiles」包,使得用戶可以指定在Excel文件將被存儲:如何指定用R-shiny和shinyFiles保存文件的文件和路徑?

server.R 庫(有光澤) 庫(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) 
} 

和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") 
))) 

儘管發現類似的問題,我一直在試圖圍繞2小時(恥辱..),將是感謝幫助

的所有例子
+1

我認爲這裏有一個誤解。 'shinyFiles'應該是'服務器端文件訪問的閃亮擴展名',而不是用於選擇客戶端文件。要保存文件,只需使用普通的'downloadButton'和相關的'downloadHandler'。 –

+0

我是R閃亮的新手,所以誤會是可能的,但我希望用戶能夠選擇他要保存文件的位置,也就是說,如果我是正確的,與downloadButton不同。 –

+0

文件下載通常由網頁瀏覽器處理,並非HTML控制(因爲網頁不應該看到本地硬盤,所以存在安全問題)。如果你的用戶使用Firefox,他們可以這樣做http://www.pcworld.com/article/217112/missing_downloads.html但通常這是非常特定的瀏覽器 –

回答

4

這是一個工作示例。同樣,這假設您在自己的計算機上運行應用程序,並且允許用戶訪問此計算機上的文件夾。您可以設置其中允許用戶將文件保存在根文件夾(見UserFolder,用戶將可以選擇這種根的任何子目錄)

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)