I'm trying to write a function to wrap up some data frames for export to Excel using the openxlsx
package. It fails when running from a downloadHandler
function in a Shiny app, but runs fine on the console in R.
Regular R script that runs fine:
library(openxlsx)
datDf1 <- data.frame(grr = c(1:10),
hrm = c(11:20),
boo = c(21:30))
datDf2 <- data.frame(will = c(31:40),
this = c(41:50),
work = c(51:60))
addSheetFun <- function(df, datName){
addWorksheet(wbExp, sheetName=datName)
writeData(wbExp, sheet=datName, df)
freezePane(wbExp, sheet=datName, firstRow=TRUE)
setColWidths(wbExp, sheet=datName, widths="auto", cols=1:ncol(df))
}
wbExp <- createWorkbook()
addSheetFun(datDf1, "SheetOne")
addSheetFun(datDf2, "SheetTwo")
Shiny application fails:
ui.r
shinyUI(
fluidPage(
downloadButton("xlExl", "Click to Export")
)
)
server.r
library(openxlsx)
library(shiny)
shinyServer(
function(
input, output, session
){
addSheetFun <- function(df, datName){
addWorksheet(wbExp, sheetName=datName)
writeData(wbExp, sheet=datName, df)
freezePane(wbExp, sheet=datName, firstRow=TRUE)
setColWidths(wbExp, sheet=datName, widths="auto", cols=1:ncol(df))
}
output$xlExl <- downloadHandler(
filename="Test.xlsx",
content=function(file){
datDf1 <- data.frame(grr = c(1:10),
hrm = c(11:20),
boo = c(21:30))
datDf2 <- data.frame(will = c(31:40),
this = c(41:50),
work = c(51:60))
wbExp <- createWorkbook()
addSheetFun(datDf1, "SheetOne")
addSheetFun(datDf2, "SheetTwo")
saveWorkbook(wbExp, file, overwrite=TRUE)
}
)
}
)
The error I get when running from Shiny is: "Warning: Error in %in%: object 'wbExp' not found [No stack trace available]"
I played around with tacking this this to the top of addSheetFun
:
if (exists("wbExp")) {
wbExp <- wbExp
}
else {
wbExp <- createWorkbook()
}
and then calling it like so:
wbExp <- addSheetFun(datDf1, "SheetOne")
wbExp <- addSheetFun(datDf2, "SheetTwo")
but that only manages to overwrite the first sheet with the second.
Thoughts?