使用R Shiny一键下载多个csv文件(downloadhandler)

MBn*_*nnn 5 csv r shiny

*嗨,我正在尝试从一个唯一的excel文件中下载多个csv文件。我想从Excel文件中下载(仅使用一个下载按钮)差异表。我不明白为什么for()循环不起作用,并且我看不到该怎么办?如果有人知道..

关键是要下载不同的csv文件,这些文件位于“ wb”列表中(wb [1],wb [2] ...)谢谢。这是我的代码,例如,处理第三张纸的代码(对不起我的英语不好):ui:

library(readxl)
library(shiny)
library(XLConnect)
fluidPage(
titlePanel("Export onglets en CSV"),
  sidebarLayout(
    sidebarPanel(
      fileInput('fichier1','Choisissez votre fichier excel :',
                accept = ".xlsx"),
      fluidPage(
    fluidRow(
      column(width = 12,
             numericInput("sheet","Indiquez l'onglet à afficher :",min = 1, value = 1),
             tags$hr(),
             textInput('text',"Indiquez le nom des fichiers :"),
             tags$hr(),
             h4("Pour télécharger les fichiers .csv :"),
             downloadButton("download","Télécharger")
             )

    )
  )),
mainPanel(
  tabsetPanel(
    tabPanel('Importation',
             h4("Fichier de base:"),
             dataTableOutput("contents"))
      )
    )
  )
)
Run Code Online (Sandbox Code Playgroud)

服务器:

function(input,output){

  #Création data :
  data <- reactive({
    inFile<- input$fichier1
    if (is.null(inFile)){
      return(NULL)
    }else{
      file.rename(inFile$datapath,
              paste(inFile$datapath,".xlsx", sep =""))
      wb = loadWorkbook(paste(inFile$datapath,".xlsx",sep=""))
      lst = readWorksheet(wb,sheet = getSheets(wb))
      list(wb = wb, lst = lst)
    }
  })



  #Sortie de la table :
  output$contents <- renderDataTable({
    data()$wb[input$sheet]
  },options = list(pageLength = 10))


  #Téléchargement :
  output$download <- downloadHandler(

    #for (i in 1:input$sheet){

    filename = function(){
      paste(input$text,"_0",3,".csv",sep = "")
    },
    content = function(file){
      write.table(data()$wb[3],file,
                  sep = ';', row.names = F, col.names = T)
    }
#}
  )
}
Run Code Online (Sandbox Code Playgroud)

Nic*_*icE 5

正如@BigDataScientist指出的那样,您可以压缩所有csv文件并下载压缩文件。您downloadHandler可能看起来像:

output$download <- downloadHandler(
    filename = function(){
      paste0(input$text,".zip")

    },
    content = function(file){
      #go to a temp dir to avoid permission issues
      owd <- setwd(tempdir())
      on.exit(setwd(owd))
      files <- NULL;

      #loop through the sheets
      for (i in 1:input$sheet){
        #write each sheet to a csv file, save the name
        fileName <- paste(input$text,"_0",i,".csv",sep = "")
        write.table(data()$wb[i],fileName,sep = ';', row.names = F, col.names = T)
        files <- c(fileName,files)
      }
      #create the zip file
      zip(file,files)
    }
  )
Run Code Online (Sandbox Code Playgroud)

这不是从excel文件下载所有工作表,而是从1到用户在中输入的任何工作表input$sheet

如果用户尚未添加excel文件/名称,您也可以禁用下载按钮。