Last active
November 5, 2021 06:09
-
-
Save tohagan/f107e6ff87d253092351092aa76474d7 to your computer and use it in GitHub Desktop.
Download CSV and PNG
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Copyright 2021 Anthony M. J. O'Hagan | |
* MIT License | |
*/ | |
/** | |
* Convert Quasar QTable rows/columns to CSV format string | |
* @param {*} columns QTable columns | |
* @param {*} rows QTable rows | |
* @returns CSV as a string | |
*/ | |
export function toCsv(columns, rows) { | |
const heading = columns.map(c => c.label).join(","); | |
return heading + "\n" + rows.map(row => { | |
return columns.map(col => { | |
let val; | |
if (typeof col.field === "string") val = row[col.field]; | |
else if (typeof col.field === "function") val = col.field(row); | |
if (typeof col.format === "function") val = col.format(val); | |
if (val === null || typeof val === "undefined") return ""; | |
val = val.toString(); | |
// FIXME: Needs a bug fix to check for single quotes in cell values. | |
if (val.includes(",")) return `"${val.replace('"', '""')}"`; | |
return val; | |
}).join(","); | |
}).join("\n"); | |
} | |
/** | |
* Download QTable as a CSV file | |
* Requires QTable data to reside in memory (non-virtual) | |
* @param {*} filename .csv file name | |
* @param {*} columns QTable columns | |
* @param {*} rows QTable rows | |
* @param {*} disposeAfter dispose | |
*/ | |
export function csvDownload(filename, columns, rows) { | |
var csv = toCsv(columns, rows); | |
var blob = new Blob([csv], {type: 'text/csv'}); | |
// <a href='blob:...' download='myfile.csv' /> | |
const href = window.URL.createObjectURL(blob); | |
const el = document.createElement("a"); | |
Object.assign(el, { href, download: filename }).click(); | |
// dispose blob and el after 1 min | |
setTimeout(() => { window.URL.revokeObjectURL(href); el.remove(); }, 60000); | |
} | |
/** | |
* Export and download a Chart / canvas | |
* @param {*} filename .png file name | |
* @param {*} canvas <canvas> element | |
*/ | |
export function canvasDownload(filename, canvas) { | |
// <a href='blob:...' download='myfile.png' /> | |
const href = canvas.toDataURL(); | |
const el = document.createElement("a"); | |
Object.assign(el, { href, download: filename }).click(); | |
// dispose blob and el after 1 min | |
setTimeout(() => { window.URL.revokeObjectURL(href); el.remove(); }, 60000); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment