QueryRunnerBS5/js/Extensions.js

68 lines
1.5 KiB
JavaScript

// Process a jQuery element's text for CSV:
$.prototype.getCellText = function()
{
var a = this.text();
["\n", "\t", "\r"].forEach(
function (i) {
a = a.replaceAll(i, "")
});
a = a.replace(/\s+/ig, " ").trim();
a = a.replace(/\"/ig, "\"\"");
return a;
};
// Trigger downloading a table as CSV:
$.prototype.exportCSV = function(options)
{
options = options || {};
if (this.prop("tagName") !== "TABLE")
throw "Element is not a table so it is not being exported.";
var output = "";
if (options.warning)
output += `; ${options.warning}\n`;
this.find("thead tr").each(function(i1, x1) {
x1 = $(x1);
x1.find("th").each(function(i2, x2) {
x2 = $(x2);
var cellText = x2.getCellText();
output += `\"${cellText}\",`;
});
output += "\n";
});
this.find("tbody tr").each(function(i1, x1) {
x1 = $(x1);
if (!x1.is(":visible"))
return;
x1.find("td").each(function(i2, x2) {
x2 = $(x2);
var cellText = x2.getCellText();
output += `\"${cellText}\",`;
});
output += "\n";
});
var filename = moment().format("yyyyMMDDhhmm");
if (typeof(options.name) === "string")
filename = `${filename}_${options.name}`;
var blob = new Blob([output], {type: "text/csv"});
var a = document.createElement("a");
a.download = `${filename}.csv`;
a.href = window.URL.createObjectURL(blob);
a.click();
};