Supress rownames in data table on download only

Viewed 111

I have the following code that allows me to download the datatable in Excel. Below I suppress row names. However is it possible to just suppress the row names on the download only? I would still like for them to show up when I view the table in Shiny.

format_fixed_table <- function(input_data, file_name){
  result <- datatable(input_data, extensions = 'Buttons',rownames= FALSE,
                      options = list(dom = 'Bfrtip',
                                     scrollX = TRUE,
                                     lengthMenu = c(10, 20, 50),
                                     pageLength = 10,
                                     buttons = list(list(extend='excel', filename=file_name)),
                             
                      ))
}
1 Answers

The column of row names is the 0-th column. You can assign a class to this column with the columnDefs option, e.g. rownames, and use the exportOptions option to select the columns which do not have this class, with the :not selector:

library(DT)

datatable(
  iris[1:5,], 
  extensions = 'Buttons', 
  rownames= TRUE,
  options = list(
    dom = 'Bfrtip',
    columnDefs = list(
      list(
        targets = 0, className = "rownames"
      )
    ),
    buttons = list(
      list(
        extend = 'excel', 
        filename = "XLSXFILE",
        exportOptions = list(
          columns = ":not(.rownames)"
        )
      )
    )
  )
)
Related