Search code examples
rdatatablerdatarexcelshiny-reactivity

convert Datatable to csv file in R


I uploaded an excel file into shiny R using following code:

Server.r

#reative function to read a table
MDPData<-reactive({
  file1<-input$MDPhistorical
  if(is.null(file1)){return()}
  z<-as.data.frame(read.xlsx(file1$datapath,sheetName = 'Probability Matrix'))      
})

#file info  
output$MDPDataTable<-DT::renderDataTable({
  if(is.null(MDPData())){return()}
  MDPData()
  DT::datatable(MDPData(),extensions = 'Responsive', options = list(pageLength=3), class = 'cell-border stripe', selection = "single")
})

relevant codes for ui.r:

fluidRow(
  box(
    title = "Historical Data of different conditions", status = "primary", solidHeader = TRUE,
    collapsible = TRUE,
    DT::dataTableOutput("MDPDataTable")
   )
)

Then I want to save MDPDataTable as a csv file. I tried to use write.csv :

write.xlsx(MDPDataTable,'www/probabilitymatrix.csv')

and the Error is as follows:

Warning: Error in is.data.frame: object 'MDPDataTable' not found
Stack trace (innermost first):
    42: is.data.frame
    41: write.xlsx
    40: server [C:\Users\foad\Desktop\DSS Journal\NSS Protorype\Nss-28-2-17/server.R#902]
     1: shiny::runApp
Error in is.data.frame(x) : object 'MDPDataTable' not found

Solution

  • It is not working and Error appears because as MrFlick said, Your write.xlsx(...) function must be in reactive object. I guess You are using ShinyApp and to download data you have a downloadButton, then the code would look like that:

    ui.R:

    downloadButton('download',label='Download data')

    server.R:

    output$download <- downloadHandler( "probabilitymatrix.csv", content = function(file) { write.xlsx(MDPData(),'www/probabilitymatrix.csv')})