How to download compared_df html table output as an html file using downloadhandler

Hello,

I have an R shiny app using the compare_df function as part of the compareDF package and it produces an HTML output. I was wondering how to export this as an HTML file using downloadHandler? This is my attempt:

Partial Code:

ui <- fluidPage(
sliderPanel(
   downloadButton("Export_HTML", "Export as Data Listing")
  ),
  # Main panel for displaying outputs ----
  mainPanel(uiOutput('html'))
  )

server <- function(input,output){

  a <- c("1","2","3")

  diff <- compare_df(filedata2, filedata1, group_col = a)

  output$html <- renderUI({
      HTML(knit2html(text=diff[["html_output"]], fragment.only=TRUE))
  })

  output$Export_HTML <- downloadHandler(
    filename = function() {
      paste("Comparison-", Sys.Date(), ".html", sep = "")
    },
    content = function(file) {

      saveWidget(as_widget(diff[["html_output"]]), file, selfcontained = TRUE)
    }
  )
}

This should do what you want...the trick is to converting the result of compare_df() to an htmlwidget, so that you can treat just like any other htmlwidget (i.e., use htmlwidgets::saveWidget() as well as shiny output/render helpers). IMO the compareDF package should make this easier...

library(shiny)
library(compareDF)
library(htmlTable)

ui <- fluidPage(
  sidebarPanel(
    downloadButton("Export_HTML", "Export as Data Listing")
  ),
  # Main panel for displaying outputs ----
  mainPanel(htmlTableWidgetOutput('diff_table'))
)

server <- function(input,output){
  
  old_df <- data.frame(var1 = c("A", "B", "C"),
                      val1 = c(1, 2, 3))
  new_df <- data.frame(var1 = c("A", "B", "C"),
                      val1 = c(1, 2, 4))
  diff <- compare_df(new_df, old_df, c("var1"))
  diff_widget <- htmlTableWidget(diff$html_output)
  
  output$diff_table <- renderHtmlTableWidget({
    diff_widget
  })
  
  output$Export_HTML <- downloadHandler(
    filename = function() {
      paste("Comparison-", Sys.Date(), ".html", sep = "")
    },
    content = function(file) {
      saveWidget(diff_widget, file, selfcontained = TRUE)
    }
  )
}

shinyApp(ui, server)
1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.