Im trying to save two data frames in one xlsx file, each one in a different sheet. The thing is that each data frame is a reactive object that depends on the same action button to generate them. The code in the download is like this:
output$downloadtable <- downloadHandler(
filename = function(){
paste("file.csv")
},
content = function(file){
write.xlsx(dataframe1(), file, row.names = FALSE, sheetName = "Hoja1")
write.xlsx(dataframe2(), file, row.names = FALSE, append = TRUE, sheetName = "Hoja2")
}
)
The problem is that I only get in my excel file the "Hoja2" sheet with the second data frame and not the first one... Somebody knows what might be wrong with this?
library(openxlsx)
filename = function() {
"mydata.xlsx"
},
content = function(file) {
g= openxlsx::createWorkbook()
openxlsx::addWorksheet(wb,"Hoja1")
openxlsx::writeData(wb,"Hoja1",dataframe1())
openxlsx::addWorksheet(wb,"Hoja2")
openxlsx::writeData(wb,"Hoja2",dataframe2())
openxlsx::saveWorkbook(g,file)
}
Related
I am working on a shiny app where the user will upload an excel file, the data will be manipulated, and then a new excel file with this data is exported for the user to examine. I am having issues with the downloadHandler function. I used to create an entirely new excel file every time based on the uploaded data like this:
output$export <- downloadHandler(
filename = "answers.xlsx",
content = function(file){
write.xlsx(exportdata(), file)
})
})
This works fine.
Now I would like to edit an excel file that I will include when I publish the app and allow the user to download this edited version like this:
output$export <- downloadHandler(
filename = "answers.xlsx",
content = function(file){
wb <- loadWorkbook("6rep-charts.xlsx")
writeData(wb, sheet = "Species Match Results", correlInput())
writeData(wb, sheet = "BS1 Data", bs1Input())
writeData(wb, sheet = "BS2 Data", bs2Input())
saveWorkbook(wb, file)
})
However, this results in the error Warning: Error in write_file: Expecting a single string value: [type=character; extent=0]. [No stack trace available]. I am not sure what is going wrong as when I run the content section outside of the shiny app, it works just fine. The problem seems to be in the saveWorkbook command.
The reason I would like to edit an existing excel file rather than create a new one is that the template file I'm including in the app has charts already made that should change when the new data is written into the file. The users would like to be able to edit these charts themselves, rather than just see a picture of a graph. If anyone has a simpler way to accomplish this, that would be great! Thank you in advance for your help!
Reproducible example using this excel file:
library(shiny); library(readxl); library(xlsx)
ui <- shinyUI(fluidPage(
titlePanel("Old Faithful Geyser Data"),
fluidRow(
column(3,
downloadButton(outputId = "export",
label = "Export Results to Excel")
),
column(6,
dataTableOutput("data")
))))
server <- function(input, output) {
adata <- faithful[1:20,]
bdata <- faithful[21:50,]
cdata <- faithful[51:200,]
read_excel_allsheets <- function(filename, tibble = FALSE) {
sheets <- readxl::excel_sheets(filename)
x <- lapply(sheets, function(Y) {readxl::read_excel(filename, sheet = Y)})
if(!tibble) x <- lapply(x, as.data.frame)
names(x) <- sheets
x
}
output$data <- renderDataTable({
adata })
output$export <- downloadHandler(
filename = "answers.xlsx",
content = function(file){
wb <- loadWorkbook("./Data/template.xlsx")
writeData(wb, sheet = "Alpha", adata)
writeData(wb, sheet = "Beta", bdata)
writeData(wb, sheet = "Gamma", cdata)
saveWorkbook(wb, file="./Data/temp.xlsx", overwrite = T)
print("done")
Fin_WB<- read_excel_allsheets("./Data/temp.xlsx")
write.xlsx(Fin_WB, file)
} ) }
shinyApp(ui = ui, server = server)
Simpler solution (I am unable to leave comments due to too low reputation):
output$export <- downloadHandler(
filename = "answers.xlsx",
content = function(file){
wb <- loadWorkbook("./Data/template.xlsx")
writeData(wb, sheet = "Alpha", adata)
writeData(wb, sheet = "Beta", bdata)
writeData(wb, sheet = "Gamma", cdata)
saveWorkbook(wb, file="./Data/temp.xlsx", overwrite = T)
file.copy(from = "./Data/temp.xlsx", to = file)
})
No need for the function read_excel_allsheets.
The saveWorkbook function does not like to operate as a write function for the content function. Confusing yes, but we can still use it within the content function, just not as the final step. We have to use a classic write function such as write.xlsx to satisfy the content function which is expecting the file and file path to write to.
To get around this we create a temp file in the Data folder (this folder will be in the dir with server and ui, and will be published). The program reads in the template file (see special function below), modifies it, and then writes/overwrites the temp file. This temp file is then read in and assigned by read.xlsx and then written to by write.xlsx. This satisfies the content function and allows us to use a template for export.
read_excel_allsheets <- function(filename, tibble = FALSE) {
sheets <- readxl::excel_sheets(filename)
x <- lapply(sheets, function(X) readxl::read_excel(filename, sheet = X))
if(!tibble) x <- lapply(x, as.data.frame)
names(x) <- sheets
x
}
output$export <- downloadHandler(
filename = "answers.xlsx",
content = function(file){
wb <- loadWorkbook("./Data/template.xlsx")
writeData(wb, sheet = "Alpha", adata)
writeData(wb, sheet = "Beta", bdata)
writeData(wb, sheet = "Gamma", cdata)
saveWorkbook(wb, file="./Data/temp.xlsx", overwrite = T)
print("done")
Fin_WB<- read_excel_allsheets("./Data/temp.xlsx")
write.xlsx(Fin_WB, file)
})
}
In order to read in all the sheets, we cannot simply use read.xlsx as it wont look at all the sheets. Using a function created here by Jeromy Anglim, we can read in all the sheets from excel. This is the read_excel_allsheets function.
I am trying to add source information to a downloaded table which contains a dataframe. I am using the download file handler to download the file. I have implemented downloading of just the dataframe without appending additional text and that works fine. On attempting to add text with the table, I get the csv formatted download file but the source information is missing and the last row has NA in the 1st and 2nd column respectively. Rest of the last row is empty.
Here is my code for the download handler that do not produce the appended text output:
downloadHandler(
filename = function() {
paste("Estimation_", Sys.Date(), ".csv", sep="")
},
content = function(file) {
df <- localTable()
df[nrow(df)+1,] <- NA
df[nrow(df),1] <- "Source: This is the source information for the table"
write.csv(df,
file,
na = "",
row.names=FALSE,
append = TRUE)
},
contentType = "text/csv",
outputArgs = list(label = "Download Table")
)
On the other hand I have tried the same functionality separately that works fine. Here is the code I used in a separate R script that does the same thing.
df = data.frame(hello=rnorm(1:5), world=rnorm(1:5));
df[nrow(df)+1,] <- NA
df[nrow(df),1] <- "Source: This is the source information for the table"
write.csv(df,
file ="abc.csv",
na = "",
row.names=FALSE)
I do not know if the issue is with Shiny in particular or something else. Please note that I am using this code as part of Flexdashboard that runs a RMD file to generate the output.
I have tried several other ways of creating the dataframe like the one below; and then passing to the downloadHandler but no luck.
dlTable <- reactive({
df_results <- localTable()
df_notes <- "Source: This is the source information for the table"
df_to_dl <- rbindlist(list(df_results,df_notes))
return(df_to_dl)
})
Any suggestion and help is highly appreciated.
Thanks
I have an RShiny application where I'm displaying multiple data-frames across different tab-setted panels. I want to be able to write data-frames appearing across each panel to one csv file per panel. I am currently trying to render this using Shiny's downloadHandler option.
Did a little bit of research and found out I could use the sink() function to divert R output to a file.
Here's my attempt at trying to incorporate sink() into one such button on the server.R side
output$downloadDemographic <- downloadHandler(
filename = function() {
paste('Demographics', '.csv', sep='')
},
content = function(file) {
sink("Demographics.csv")
cat('Population Demographics')
write.csv(Population)
cat('Geography Demographics')
write.csv(Geography)
sink()
}
)
where Population and Geography are two data-frames with the same number of columns but different names.
The sink function automatically writes the above dataframes to a csv file 'Demographics.csv' into my working directory but the downloadHandler option on Shiny prompts the user to save the csv file on the fly. Kind of contradicting what I am trying to achieve here. I'm probably missing something or making an obvious mistake, I don't know.
Desired output - https://i.stack.imgur.com/yddrE.jpg
I could render multiple download buttons, write each of the data-frames to multiple csv files but some of my tab setted elements have as many as 8 data-frames and this would make the UI messy.
or
I could coerce multiple data-frames into a single one before writing to a csv file but they are all unequal sized dataframes and formatting them into the desired output would be a huge pain.
Any thoughts on how I could establish this any other way?
Thanks!
Other options:
Write an Excel workbook with one sheet per
dataframe
Zip together multiple csv
files
Here's a sample of both options using four dataframes from the R Datasets Package.
library(shiny)
library(xlsx)
shinyApp(
ui = fluidPage(
downloadButton("downloadExcelSheet", "Download Excel Workbook with Multiple Sheets"),
downloadButton("downloadZippedCSV", "Download zipped csv files")
),
server = function(input, output) {
#### Write an Excel workbook with one sheet per dataframe ####
output$downloadExcelSheet <- downloadHandler(
filename = function() {
"excelWorkbook.xlsx"
},
content = function(file) {
# write workbook and first sheet
write.xlsx(mtcars, file, sheetName = "mtcars", append = FALSE)
# add other sheets for each dataframe
listOtherFiles <- list(iris = iris,
airquality = airquality,
sleep = sleep)
for(i in 1:length(listOtherFiles)) {
write.xlsx(listOtherFiles[i], file,
sheetName = names(listOtherFiles)[i], append = TRUE)
}
}
)
#### Zip together multiple csv files ####
output$downloadZippedCSV <- downloadHandler(
filename = function() {
"zippedCSV.zip"
},
content = function(file) {
# go to temp dir to avoid permission issues
owd <- setwd(tempdir())
on.exit(setwd(owd))
# create list of dataframes and NULL value to store fileNames
listDataFrames <- list(mtcars = mtcars,
iris = iris,
airquality = airquality,
sleep = sleep)
allFileNames <- NULL
# loop through each dataframe
for(i in 1:length(listDataFrames)) {
# write each dataframe as csv and save fileName
fileName <- paste0(names(listDataFrames)[i], ".csv")
write.csv(listDataFrames[1], fileName)
allFileNames <- c(fileName, allFileNames)
}
# write the zip file
zip(file, allFileNames)
}
)
}
)
I have a file which i generate in shiny
The user clicks a button and the file should download. However nothing happens
The function export_report generates the excel file and saves it to a location. The function then passes back the file location to the download handler so it will download the file. The problem seems to be that it isnt being returned correctly. I have tested the function (export_report) outside of shiny and it returns everything perfectly so I'm clearly doing something wrong from the shiny perspective.
The file itself is created where it is supposed to be on the server because i can download it within RStudio and see it in the file explorer. Can anyone help
# UI Section
downloadButton("downloadRpt", "Download Report")
# Server Section
output$downloadRpt <- downloadHandler(
filename = function() {
mydf <- report()
dateRange <- input$dates_report
selection <- input$selection
myfile <- export_report (mydf, selection, dateRange)
},
content = function(file) {
file.copy(myfile, file)
}
)
I have seen other examples R Shiny: Download existing file which is what my code is based on
EDIT 1: Adding the export_report function with some fake data to run it
export_report <- function(mydf,selection,dateRange) {
# Template for where the template excel file is stored
myoutputTemplate <- '/home/shiny_tutorials/Save to Database/templates/output_template.xlsx'
start_date <- dateRange[1]
end_date <- dateRange[2]
date_range <- paste(start_date ,end_date, sep = " - " )
# Load workbook the template workbook
wb <- loadWorkbook(myoutputTemplate)
# write to the workbook the data frame
writeWorksheet(wb, mydf, sheet="Details",
startRow=8, startCol=2,
header=FALSE)
# add the the customer the user selected
writeWorksheet(wb, selection, sheet="Details",
startRow=3, startCol=3,
header=FALSE)
# date
writeWorksheet(wb, date_range, sheet="Details",
startRow=5, startCol=3,
header=FALSE)
# Create The file Name
filename <- paste(selection, Sys.Date(), sep = " - ") %>%
paste(.,"xlsx", sep = ".")
# removes the % sign and extra qoutes
filename <- gsub (pattern = '\'|%','', x = filename)
# output directory
myoutput <- paste('/home/shiny_tutorials/Save to Database/output/',
filename, sep = '')
# Save workbook
saveWorkbook(wb, myoutput)
# Return File Path
myoutput
}
To call the function you can use the data below
dateRange <- c("2011-09-23","2016-09-23")
selection = "COMPANY_A"
mydf <- iris
myfile <- export_report(mydf,selection,dateRange)
EDIT 2 I have now managed to get an error out of it. When i cat(myfile) in the filename = function() { section of the code i get the error after the correct file path has been returned
Warning in rep(yes, length.out = length(ans)) :
'x' is NULL so the result will be NULL
Warning: Error in ifelse: replacement has length zero
Stack trace (innermost first):
1: runApp
Error : replacement has length zero
This error is basically because my file path does not get passed to the segment myfile so
if someone can tell me how to get the filepath generated by my function to the server section of the code below, that should fix my problem
content = function(file) {
file.copy(myfile, file)
}
Thank you to everyone who commented and clarified my thinking a bit on how the download handler works.
In the end, i created a new function which split up the export function above
The new function i used is called generate_file() which simply returns the file name
generate_file_name <- function(selection) {
# Create The file Name
filename <- paste(selection, Sys.Date(), sep = " - ") %>%
paste(.,"xlsx", sep = ".")
# removes the % sign and extra qoutes
filename <- gsub (pattern = '\'|%','', x = filename)
# output directory
myoutput <- paste('/home/shiny_tutorials/Save to Database/output/',
filename, sep = '')
# Return File Path
myoutput
}
Then in the server side
output$downloadRpt <- downloadHandler(
filename = function() {
selection <- input$company
generate_file_name(selection)
},
content = function(file) {
mydf <- report()
dateRange <- input$dates_report
selection <- input$company
export_report(mydf,selection,dateRange)
myfile <- generate_file_name(selection)
file.copy(myfile, file)
}
)
This then finds the newly created file and exports it for the user
I just checked your problem with this example code and it worked:
output$downloadData <- downloadHandler(
filename = function() {
data <- mtcars
myfile <- "data.csv"
write.csv(data, myfile)
myfile
},
content = function(file) {
print(file) //prints: [...]\\Local\\Temp\\RtmpEBYDXT\\fileab8c003878.csv
file.copy(file, file)
}
)
myfile is the filename of the downloaded file. You cannot use it in file.copy as input, this variable is out of scope. It seems that R creates a temp file name (see the print()).
Try to use the filename function to define your path or a custom file name, and the write.csv in the content part. Example code:
output$downloadData <- downloadHandler(
filename = function() {
paste(<user_name or date for eg>, ".csv", sep="")
},
content = function(file) {
write.csv(data, file)
}
)
I noticed in your comment above, you have asked how the application would generate the correct file when used by multiple users. For this part, you need to use the session.
So if your business logic functions were to come from an R file called foo.R, the server code should look something like:
shinyServer(func = function(input, output, session) {
source("./foo.R", local=TRUE)
......
And this would separate out the session for each user, thereby generating files specific to each, when downloading. Hope this gives you some pointers.
I am using the R package Shiny to develop my own web application.
I have a download button which permits me to export the data into a excel file. In the excel file, there are 4 sheets and in each of them there is a data frame.
For example, in sheet1 there is dataTab1, in sheet2 there is dataTab2, in sheet 3 there is dataTab3 and in sheet4 there is dataTab4.
For doing this, I am using the function downloadHeader() in shiny server.R.
I have used two methods to do this.
Method 1: using the R package xlsx
output$downloadTab <- downloadHandler(
filename = "dataxls.xlsx",
content = function(file) {
#creation of the workbook
dataxls=createWorkbook(file)
#creation of the sheets
dataTabs1=createSheet(wb=dataxls,sheetName="Compartiments-simulation_sans_changement")
dataTabs2=createSheet(wb=dataxls,sheetName="Esperance-simulation_sans_changement")
dataTabs3=createSheet(wb=dataxls,sheetName="Compartiments-simulation_avec_changement")
dataTabs4=createSheet(wb=dataxls,sheetName="Esperance-simulation_avec_changement")
#add the dataframes to the sheets
writeWorksheet(dataxls, dataTab1, sheet = "Compartiments-simulation_sans_changement")
writeWorksheet(dataxls, dataTab2, sheet = "Esperance-simulation_sans_changement")
writeWorksheet(dataxls, dataTab3, sheet = "Compartiments-simulation_avec_changement")
writeWorksheet(dataxls, dataTab4, sheet = "Esperance-simulation_avec_changement")
saveWorkbook(dataxls,file)
}
)
The problem is that I have the following error:
Error in createWorkbook(file) :
Unknown format C:\Users\Baramova\AppData\Local\Temp\Rtmpmyqyeh\fileafc6d2b5998.xlsx
I have tried to fix it using the following example:
content = function(file) {
fname = paste(file,"xlsx",sep=".")
wb = loadWorkbook(fname, create = TRUE)
createSheet(wb, name = "Sheet1")
writeWorksheet(wb, c(1:3), sheet = "Sheet1")
saveWorkbook(wb)
file.rename(fname,file)
}
But it doesn't work for me. Maybe I am omitting something.
Do you have any idea?
Method 2: using RODBC package
output$downloadTab <- downloadHandler(
filename ="Tab.xls",
content = function(fname) {
tmpdir <- tempdir()
db <- paste(tmpdir,fname,sep="/")
channel <- odbcConnectExcel(xls.file = db,readOnly=FALSE)
sqlSave(channel, Compartiments_simulation_sans_changement, tablename = "Compartiments_simulation_sans_changement")
sqlSave(channel, Esperance_simulation_sans_changement, tablename = "Esperance_simulation_sans_changement")
sqlSave(channel, Compartiments_simulation_avec_changement, tablename = "Compartiments_simulation_avec_changement")
sqlSave(channel, Esperance_simulation_avec_changement, tablename = "Esperance_simulation_avec_changement")
odbcClose(channel)
},
contentType="application/csv"
)
The problem is that the odbcConnectExcel() function is not recognized even if I have called the RODBC package by typing:
library(RODBC)
Do you have any idea why is that so?
I have found the solution of my problem.
Firstly you have to call the XLConnect and the RODBC packages.
After that, you could use the following example:
output$downloadTab <- downloadHandler(
filename ="Tab.xls",
content = function(file) {
write.csv(Compartiments_simulation_sans_changement, file="Compartiments-simulation_sans_changement.csv")
write.csv(Esperance_simulation_sans_changement, file="Esperance-simulation_sans_changement.csv")
write.csv(Compartiments_simulation_avec_changement, file="Compartiments-simulation_avec_changement.csv")
write.csv(Esperance_simulation_avec_changement, file="Esperance-simulation_avec_changement.csv")
channel <- odbcConnectExcel(xls.file = file,readOnly=FALSE)
sqlSave(channel, Compartiments_simulation_sans_changement, tablename = "Compartiments_simulation_sans_changement")
sqlSave(channel, Esperance_simulation_sans_changement, tablename = "Esperance_simulation_sans_changement")
sqlSave(channel, Compartiments_simulation_avec_changement, tablename = "Compartiments_simulation_avec_changement")
sqlSave(channel, Esperance_simulation_avec_changement, tablename = "Esperance_simulation_avec_changement")
odbcClose(channel)
},
contentType="application/xls"
)