Search code examples
rcsvbuttondownloadr-markdown

how create a download button to get a .csv in rmarkdown (without using shiny)?


I need to add a download button to my report (html), were if you click on, it will download a .csv. I'm working with r markdown (i cannot use shiny). I have been trying even with json codeing, but nothing.

The following code opens another tab with an error.

library(openxlsx)
library(jsonlite)

temp_file <- tempfile(fileext = ".csv")
write.csv(bd_g_summ, file = temp_file, row.names = FALSE)

<button onclick="descargarCSV()">Descargar CSV</button>

<script>
function descargarCSV() {
  var link = document.createElement("a");
  link.href = "{{temp_file}}";
  link.download = "dataframe_autocompletado.csv";
  link.click();
}
</script>

Here's the head of "bd_g_summ":

head(bd_g_summ)
# A tibble: 6 x 6
# Groups:   EID [4]
  EID                Notes_Nueva         peso_inicial peso_final fecha_inicial fecha_final
  <chr>              <chr>                      <dbl>      <dbl> <date>        <date>     
1 ""                 Hijos del Rodeo VIP         142.        97  2023-03-23    2023-03-27 
2 ""                 La Angelita                 152.       200. 2023-03-10    2023-05-10 
3 "032 010001229420" Los Leones                  130        130  2023-03-08    2023-03-08 
4 "032 010001229421" Los Leones                  160.       160. 2023-03-08    2023-03-08 
5 "032 010001229421" NA                          189        189  2023-06-30    2023-06-30 
6 "032 010001229422" Los Leones                  168.       168. 2023-03-08    2023-03-08 

Solution

  • Easy just add a button to the table like this:

    datatable(
      iris, extensions = 'Buttons', options = list(
        dom = 'Bfrtip',
        buttons = c('csv')
      )
    )