Embed csv in html rmarkdown
How about something like this:
---
title: "Reproducable Example"
author: "dimitris_ps "
date: "17 December 2016"
output: html_document
---
<style>
#DataTables_Table_0 {
visibility: hidden;
}
#DataTables_Table_0_paginate {
visibility: hidden;
}
</style>
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(DT)
dt <- datatable(mtcars, rownames=T,
# filter = 'top',
callback=JS('$("a.buttons-collection").css("background","#008CBA");
$("a.buttons-collection").css("font-size","15px");
$("a.buttons-collection").css("border-radius", "8px");
$("a.buttons-collection").css("margin-right","0px");
return table;'),
extensions = 'Buttons',
options = list(searching=F,
paging = T,
bInfo = F,
columnDefs = list(list(className = 'dt-left', targets = 0),
list(className = 'dt-center', targets = 1:11)),
pageLength = 1,
initComplete = JS("function(settings, json) {",
"$(this.api().table().header()).css({'background-color': '#99ccff', 'color': '#003333'});",
"}"),
dom = 'Bfrtip',
buttons = list(
list(extend = 'collection',
buttons = c('excel', 'csv'),
text = 'DOWNLOAD DATA')
)
)
)
```
<br>
```{r mtcars, echo=FALSE}
dt
```
You will need to have the DT
library installed
No javascript; no widgets; no extra CSS; 4 LoC (cld be 1 LoC if you like unreadable code):
```{r}
write.csv2(mtcars, "./file.csv")
library(magrittr)
readLines("./file.csv") %>%
paste0(collapse="\n") %>%
openssl::base64_encode() -> encoded
```
[Download CSV](`r sprintf('data:text/csv;base64,%s', encoded)`)
Fairly straightforward:
- treat the file as just "stuff" and read it in as lines
- make it all one blob of newline separated text
- encode it into base 64
- make a data URI with the proper media type
- embed it as a markdown link
You can also do something like:
<a download="mtcars.csv" href="`r sprintf('data:text/csv;base64,%s', encoded)`">Straight HTML Download Link</a>
if you want to give browsers (and, hence, users) a suggested filename (HTML placement in markdown rules apply).
NOTE:
readBin("./file.csv", "raw", file.info("./file.csv")$size) %>%
openssl::base64_encode() -> encoded
also works equally as well as the readLines()
version.