Downloading Excel File from XLConnect with R Shiny

穿精又带淫゛_ 提交于 2019-12-20 09:03:33

问题


Has anyone tried using the download handler in R Shiny to download a freshly created Excel file with XLConnect?

In the ui.R there is the unremarkable line:

downloadButton('downloadData', 'Download')

In the server.R there is the handler:

output$downloadData <- downloadHandler(

filename = function() { "output.xlsx" },

    content = function(file){
      wb <- loadWorkbook(file, create = TRUE)
      createSheet(wb, name = "Sheet1")
      writeWorksheet(wb, c(1:3), sheet = "Sheet1") # writes numbers 1:3 in file
      saveWorkbook(wb)
    }
)

I have no problem downloading a .csv and no problem creating the excel file with XLConnect. But when I run the code as above I get the following error in my Chrome browser:

IllegalArgumentException (Java): File extension "file1b683b9323bc" not supported! Only *.xls and *.xlsx are allowed!

As far as I can see, XLConnect cannot write to a temporary file.

Has anyone got a solution or workaround?

One option would be to save the file in a specific location and then creating a download link pointing to it. However, this is not very Shiny-esque as multiple users would cause havok.

Many Thanks

Marcus


回答1:


Try using this for the content(...) function; it works for me...

content = function(file){
      fname <- paste(file,"xlsx",sep=".")
      wb <- loadWorkbook(fname, create = TRUE)
      createSheet(wb, name = "Sheet1")
      writeWorksheet(wb, c(1:3), sheet = "Sheet1") # writes numbers 1:3 in file
      saveWorkbook(wb)
      file.rename(fname,file)
    }

The problem is that file is a randomly generated temp file, without an extension, whereas saveWorkbook(...) requires the .xlsx extension. So this just appends .xlsx to file and uses that for all the XLConnect manipulations, then renames the final file to the original name (e.g., strips off the extension).



来源:https://stackoverflow.com/questions/21383748/downloading-excel-file-from-xlconnect-with-r-shiny

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!