如何将格式化的Excel下载到选定的目录中

时间:2018-02-05 19:42:50

标签: r excel download shiny

我希望我的Shiny应用程序将条件格式应用于结果,并让我的用户将格式化表格保存到他们选择的文件夹中。

这是我的代码。我跑的时候收到了这条消息。

Warning: Error in as.data.frame.default: cannot coerce class "structure("Workbook", package = "openxlsx")" to a data.frame

app.R:

 ui <- fluidPage(
  column(DT::dataTableOutput('sw'), width = 6),
  br(),

  downloadButton('download', "Save")
)


server <- function(input, output, session) {

  #Dummy data. Actual data is reactive.
  result <- reactive({
    a <- c (NA, 120, 91, 74)
    b <- c(120, NA, 109, 119)
    c <- c(91, 109, NA, 121)
    d <- c(74, 119, 121, NA)

    return(data.frame(a, b, c,d))
  })

  output$sw <- DT::renderDataTable({
      brks    <- quantile(result(), probs = seq(.05, .95, .05), na.rm = TRUE)
      colfunc <- colorRampPalette(c("indianred1","white","mediumseagreen"))
      clrs    <- colfunc(length(brks) + 1)
      DT::datatable(result(), rownames = TRUE, options = list(paging = FALSE, searching = FALSE))  %>% formatStyle(colnames(result()), backgroundColor = styleInterval(brks, clrs))
  })

  output$download <- downloadHandler(
    filename = function() {paste("Result.xlsx")},
    content  = function(file) {

      wb <- createWorkbook()
      negStyle <- createStyle(bgFill = "#FFC7CE")
      posStyle <- createStyle(bgFill = "#C6EFCE")

      addWorksheet(wb, "Sheet1")
      writeData(wb = wb, sheet="Sheet1", x = result(), startRow = 1, startCol = 1)

      posStyle <- createStyle(bgFill = "#C6EFCE")
      conditionalFormatting(wb, "Sheet1", cols=3:ncol(result()), rows=2:(1+nrow(result())), rule="<=80", style = negStyle)
      conditionalFormatting(wb, "Sheet1", cols=3:ncol(result()), rows=2:(1+nrow(result())), rule=">120", style = posStyle)

      write.xlsx(x = wb, file)
    }
  )
}

shinyApp(ui = ui, server = server)

更新:2/6/2018

更改以下内容

write.xlsx(x = wb, file)

saveWorkbook(wb, file)

完美无缺。

1 个答案:

答案 0 :(得分:0)

这个小脚本在我的Windows 7系统上运行良好。

library(shiny)
library(shinydashboard)
library(XLConnect)

ui <- dashboardPage(
  dashboardHeader(title = "excel download"),
  dashboardSidebar(downloadLink("downloadData", "Download")),
  dashboardBody(),
  skin = "purple"
)

server <- function(input, output) {
  data1 <- mtcars
  output$downloadData <- downloadHandler(
    filename = function(){"mtcars.xlsx"},
    content = function(file) {
      fname <- paste(file,"xlsx",sep=".")
      wb <- loadWorkbook(fname,create = TRUE)
      createSheet(wb,"cars")
      writeWorksheet(wb,data = data1,sheet = "cars")
      saveWorkbook(wb)
      file.rename(fname,file)
    },
    contentType="application/xlsx" 
  )
}

shinyApp(ui = ui, server = server)