Download formatted flextables off of shiny app

23 Views Asked by At

Is there a way to download flextables outputed in a shiny app? I know that this code is used to download tables from shiny into csv format but I would like to be able to download a flextable to word that is formatted (keeps flextable format).

# Downloadable csv of selected dataset ----
  output$downloadData <- downloadHandler(
    filename = function() {
      paste(input$dataset, ".csv", sep = "")
    },
    content = function(file) {
      write.csv(datasetInput(), file, row.names = FALSE)
    }
  )

Creating flextable in shiny example

library(shiny)
library(flextable)
library(dplyr)

dat <- mtcars %>%
  mutate(car = rownames(.)) %>%
  select(car, everything())

ui <- fluidPage(
  titlePanel("mtcars"),
  sidebarLayout(
    sidebarPanel(
      sliderInput("mpg", "mpg Limit", min = 11, max = 33, value = 20)
    ),
    mainPanel(uiOutput("mtcars_ft"))
  )
)

server <- function(input, output) {
  output$mtcars_ft <- renderUI({
    req(input$mpg)
    filter(dat, mpg <= input$mpg) %>%
      flextable() %>%
      theme_vader() %>%
      autofit() %>%
      htmltools_value()
  })
}

# Run the application
shinyApp(ui = ui, server = server)
1

There are 1 best solutions below

2
Stéphane Laurent On

Yes, like this:

library(shiny)
library(flextable)
library(dplyr)

dat <- mtcars %>%
  mutate(car = rownames(.)) %>%
  select(car, everything())

ui <- fluidPage(
  titlePanel("mtcars"),
  sidebarLayout(
    sidebarPanel(
      downloadButton("dwnld"),
      sliderInput("mpg", "mpg Limit", min = 11, max = 33, value = 20)
    ),
    mainPanel(uiOutput("mtcars_ft"))
  )
)

server <- function(input, output, session) {
  
  fxtable <- reactive({
    filter(dat, mpg <= input$mpg) %>%
      flextable() %>%
      theme_vader() %>%
      autofit()    
  })
  
  output$mtcars_ft <- renderUI({
      fxtable() %>% htmltools_value()
  })
  
  output$dwnld <- downloadHandler(
    filename = function() {
      "flextable.html"
    },
    content = function(file) {
      save_as_html(fxtable(), path = file)
    }
  )
}

# Run the application
shinyApp(ui = ui, server = server)

There are other saving functions: save_as_docx, etc. These functions have some options, see the doc.