Search code examples
rdatatable

Change filename when downloading data from datatable R


I'm using datatable inside an R shiny web app.

How can I change the file name that is gonna be created when donwloading a datatable object?

For example:

  datatable(
      iris2,
      extensions = 'Buttons', options = list(
        dom = 'Bfrtip',
        buttons = 
          list('copy', 'print', list(
            extend = 'collection',
            buttons = c('csv', 'excel', 'pdf'),
            text = 'Download'
          ))

      )
    )

I want the file donwloaded to be named by default "iris.xlsx" or "iris.csv" . Thanks


Solution

  • Because of extend = "collection", you need to include the filename argument through a nested list inside the button = list(...)

    library(DT)
    datatable(
          iris,
          extensions = 'Buttons', options = list(
            dom = 'Bfrtip',
            buttons =
              list('copy', 'print', list(
                extend = 'collection',
                buttons = list(
                    list(extend = 'csv', filename = "iris"),
                    list(extend = 'excel', filename = "iris"),
                    list(extend = 'pdf', filename = "iris")),
                text = 'Download'
              ))
          )
        )
    

    Without a collection of buttons

    If you don't want a collection of sub-buttons and instead wanted to specify a filename for a single file type (let's say a CSV file), you can do this

    library(DT)
    datatable(
        iris,
        extensions = 'Buttons', options = list(
            dom = 'Bfrtip',
            buttons =
                list('copy', 'print', list(
                    extend = 'csv',
                    title = "interesting_file"))))
    

    THe key is to use extend = "csv" to specify the file type and then use title for the filename, all inside a list.