Continuing the discussion from Dataview - Exporting Table as CSV and based on my answer to another post here, I’ve come up with an imperfect way to save dataview tables as csv fies, if that’s something you’d find useful.
This code does the following:
- Grab the data you want
- Select the columns you want in the table
- Export the table as a CSV file
Example
Note: dataviewjs
must be appended for code block
// ----- Gather data and specify table columns -----
// Grab all relevant notes/pages
let projects = dv.pages("#projects");
// Grab the columns you want using .map function
const projects_tbl = projects.map(p => [p.file.link,p.status,p.domain]);
// Map function traverses each row and joins elements with ",", then we join the array of strings with "\n"
let csvContent = "data:text/csv;charset=utf-8," + projects_tbl.map(e => e.join(",")).join("\n");
// ------ Create CSV file ------
// Create a hidden <a> DOM node and set its download attribute as follows, where "my_data.csv" will be the name of your csv file
var encodedUri = encodeURI(csvContent);
var link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download","my_data.csv");
document.body.appendChild(link);
link.click();
I would use this at your discretion, as it uses some functions I am unaware of, but suffice to say I’ve tested this and I got a table just as I wanted, as a csv file. Once this code has run, it will automatically bring up a window to save the file, and bear in mind that this will keep running if you have set dataview queries to re-evaluate in Live-Preview. So, I would run it as a script perhaps?
Would love some extra suggestions to improve upon this to make it:
- More succinct
- More flexible
- Edit: header info would be nice too
Generalisable version here:
// ----- Gather data and specify table columns -----
// Grab all relevant notes/pages
let <name_of_pages> = dv.pages("<source>");
// Grab the columns you want using .map function
const <table_name> = <name_of_pages>.map(p => [p.<field1>,p.<field2>,p.<field3>]);
// Map function traverses each row and joins elements with ",", then we join the array of strings with "\n"
let csvContent = "data:text/csv;charset=utf-8," + <table_name>.map(e => e.join(",")).join("\n");
// ------ Create CSV file ------
// Create a hidden <a> DOM node and set its download attribute as follows, where "my_data.csv" will be the name of your csv file
var encodedUri = encodeURI(csvContent);
var link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download","<csv_file_name>.csv");
document.body.appendChild(link);
link.click();