Exporting Pug column & Rows to CSV - javascript

extends layout
block content
p#demo
h1 #[Repository Name :] #{repo.name}
dd #[ IBM Github URL:]
a(href='/'+repo.url) #{repo.url}
dd #[ Repository ID:] #{repo._id}
dd #[ Language Type:] #{repo.type}
div(class='col')
div(class='col-sm-9')
p
button.hidediv Hide dependencies
button.showdiv Show dependencies
.divdemo
| Dependencies
.button
.container
#dvData
.col-sm-3(style='background-color:#5596e9;')
div(class='col-sm-2')
table
tbody
tr: th Name
tbody
each D in list_dependencies
tr
td
td #{D.name}
.col-sm-3(style='background-color:#f5f7fa;')
div(class='col-sm-2')
table
thead
tr: th Version
tbody
each D in list_dependencies
tr
td
td #{D.version}
.col-sm-3(style='background-color:#ADD8E6;')
div(class='col-sm-2')
table
thead
tr: th repository ID
tbody
each D in list_dependencies
tr
td
td #{D.repo_id}
.button.col-sm-6
a#export(href='#', role='button')
| Click On This Here Link To Export The Table Data into a CSV File
script(type='text/javascript', src='https://code.jquery.com/jquery-1.11.0.min.js')
//script(src='https://cdn.jsdelivr.net/npm/json2csv')
//script(src='/node_modules/table2csv/dist/table2csv.min.js')
//script(src='/javascript/client.js')
$(function() {
$('#register').on('click', function(event) {
event.preventDefault();
var fullname = $('#fullname').val();
var email = $('#email').val();
var password = $('#password').val();
var cpassword = $('#cpassword').val();
if (!fullname || !email || !password || !cpassword) {
$('#msgDiv').show().html('All fields are required.');
} else if (cpassword != password) {
$('#msgDiv').show().html('Passowrds should match.');
} else {
$.ajax({
url : '/register',
method : 'POST',
data : { full_name: fullname, email: email, password: password, cpassword: cpassword }
}).done(function(data) {
if (data) {
if (data.status == 'error') {
var errors = '<ul>';
$.each(data.message, function(key, value) {
errors = errors + '<li>' + value.msg + '</li>';
});
errors = errors + '</ul>';
$('#msgDiv').html(errors).show();
} else {
$('#msgDiv').removeClass('alert-danger').addClass('alert-success').html(data.message).show();
}
}
});
}
});
});
function myFunction() {
var x = document.getElementById('myDIV');
if (x.style.display === 'none') {
x.style.display = 'block';
} else {
x.style.display = 'none';
}
}
$(document).ready(function() {
$('.hidediv').click(function() {
$('.divdemo').hide('slow');
});
$('.showdiv').click(function() {
$('.divdemo').show(2000);
});
});
$(document).ready(function() {
console.log('HELLO');
function exportTableToCSV($table, filename) {
var $headers = $table.find('tr:has(th)'),
$rows = $table.find('tr:has(td)'),
// Temporary delimiter characters unlikely to be typed by keyboard
// This is to avoid accidentally splitting the actual contents
tmpColDelim = String.fromCharCode(11), // vertical tab character
tmpRowDelim = String.fromCharCode(0), // null character
// actual delimiter characters for CSV format
colDelim = '","',
rowDelim = '"\r\n"';
// Grab text from table into CSV formatted string
var csv = '"';
csv += formatRows($headers.map(grabRow));
csv += rowDelim;
csv += formatRows($rows.map(grabRow)) + '"';
// Data URI
var csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csv);
// For IE (tested 10+)
if (window.navigator.msSaveOrOpenBlob) {
var blob = new Blob([ decodeURIComponent(encodeURI(csv)) ], {
type : 'text/csv;charset=utf-8;'
});
navigator.msSaveBlob(blob, filename);
} else {
$(this).attr({
download : filename,
href : csvData
//,'target' : '_blank' //if you want it to open in a new window
});
}
//------------------------------------------------------------
// Helper Functions
//------------------------------------------------------------
// Format the output so it has the appropriate delimiters
function formatRows(rows) {
return rows.get().join(tmpRowDelim).split(tmpRowDelim).join(rowDelim).split(tmpColDelim).join(colDelim);
}
// Grab and format a row from the table
function grabRow(i, row) {
var $row = $(row);
//for some reason $cols = $row.find('td') || $row.find('th') won't work...
var $cols = $row.find('td');
if (!$cols.length) $cols = $row.find('th');
return $cols.map(grabCol).get().join(tmpColDelim);
}
// Grab and format a column from the table
function grabCol(j, col) {
var $col = $(col),
$text = $col.text();
return $text.replace('"', '""'); // escape double quotes
}
}
// This must be a hyperlink
$('#export').click(function(event) {
// var outputFile = 'export'
var outputFile =
window.prompt("What do you want to name your output file (Note: This won't have any effect on Safari)") ||
'export';
outputFile = outputFile.replace('.csv', '') + '.csv';
// CSV
exportTableToCSV.apply(this, [ $('#dvData > table'), outputFile ]);
// IF CSV, don't do event.preventDefault() or return false
// We actually need this to be a typical hyperlink
});
});
var filter = document.getElementById('filter');
// Filter event
filter.addEventListener('keyup', filterItems);
// Filter Items
function filterItems(e) {
// convert text to lowercase
var text = e.target.value.toLowerCase();
// Get lis
var items = itemList.getElementsByTagName('dl');
//var items = itemList.querySelectorAll('dd');
// Convert to an array
Array.from(items).forEach(function(item) {
var itemName = item.firstChild.textContent;
if (itemName.toLowerCase().indexOf(text) != -1) {
item.style.display = 'block';
} else {
item.style.display = 'none';
}
});
}
Hi i am trying to download to CSV from my pug file. I would like to be to download to csv with three headers name, version and repository as the columns. Then for each column i would like to have a list of rows containing (in Name d.name, in version d.version, in repoistory d.repo_id. I am using this code but when i try to download it the csv is blank. I am new to pug and was wondering if there is a way to this and if anybody can help me out as i have been spending quite a number of hours on this. Thanks in advance.

Related

How to convert dynamically generated javascript table into json/xml and how to save that file?

I've a function in javascript which creates table of properties dynamically:
// update table
PropertyWindow.prototype._update = function (text) {
if (text === void 0) { text = "<no properties to display>"; }
this._propertyWindow.html(text);
};
PropertyWindow.prototype._onModelStructureReady = function () {
this._assemblyTreeReadyOccurred = true;
this._update();
};
// create row for property table
PropertyWindow.prototype._createRow = function (key, property, classStr) {
if (classStr === void 0) { classStr = ""; }
var tableRow = document.createElement("tr");
tableRow.id = "propertyTableRow_" + key + "_" + property;
if (classStr.length > 0) {
tableRow.classList.add(classStr);
}
var keyDiv = document.createElement("td");
keyDiv.id = "propertyDiv_" + key;
keyDiv.innerHTML = key;
var propertyDiv = document.createElement("td");
propertyDiv.id = "propertyDiv_" + property;
propertyDiv.innerHTML = property;
tableRow.appendChild(keyDiv);
tableRow.appendChild(propertyDiv);
return tableRow;
};
I want to take that generated table into json/xml and save this into a new file, how would I do this?
You can basically loop through the generated table like below and convert it into json with the following code
var myRows = [];
var $headers = $("th");
//your table path here inside the selector
var $rows = $("tbody tr").each(function(index) {
$cells = $(this).find("td");
myRows[index] = {};
$cells.each(function(cellIndex) {
myRows[index][$($headers[cellIndex]).html()] = $(this).html();
});
});
// Let's put this in the object like you want and convert to JSON (Note: jQuery will also do this for you on the Ajax request)
var myObj = {};
myObj.myrows = myRows;
alert(JSON.stringify(myObj));​
Possible duplicate

.on('click', function (event) is not firing if the link is rendered inside a partial view [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 7 years ago.
I am trying to implement an export to CSV functionality inside my asp.net mvc. So i added the following link inside a partial view:-
Export Table data into Excel
and inside the _layout view i call the following script:-
$(document).ready(function () {
function exportTableToCSV($table, filename) {
var $rows = $table.find('tr:has(td)'),
// Temporary delimiter characters unlikely to be typed by keyboard
// This is to avoid accidentally splitting the actual contents
tmpColDelim = String.fromCharCode(11), // vertical tab character
tmpRowDelim = String.fromCharCode(0), // null character
// actual delimiter characters for CSV format
colDelim = '","',
rowDelim = '"\r\n"',
// Grab text from table into CSV formatted string
csv = '"' + $rows.map(function (i, row) {
var $row = $(row),
$cols = $row.find('td');
return $cols.map(function (j, col) {
var $col = $(col),
text = $col.text();
return text.replace('"', '""'); // escape double quotes
}).get().join(tmpColDelim);
}).get().join(tmpRowDelim)
.split(tmpRowDelim).join(rowDelim)
.split(tmpColDelim).join(colDelim) + '"',
// Data URI
csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csv);
$(this)
.attr({
'download': filename,
'href': csvData,
'target': '_blank'
});
}
// This must be a hyperlink
$(".export").on('click', function (event) {
// CSV
exportTableToCSV.apply(this, [$('#dvData>table'), 'export.csv']);
// IF CSV, don't do event.preventDefault() or return false
// We actually need this to be a typical hyperlink
});
});
i am using the table2CSV plugin as follow:-
jQuery.fn.table2CSV = function (options) {
var options = jQuery.extend({
separator: ',',
header: [],
delivery: 'popup' // popup, value
},
options);
var csvData = [];
var headerArr = [];
var el = this;
//header
var numCols = options.header.length;
var tmpRow = []; // construct header avalible array
if (numCols > 0) {
for (var i = 0; i < numCols; i++) {
tmpRow[tmpRow.length] = formatData(options.header[i]);
}
} else {
$(el).filter(':visible').find('th').each(function () {
if ($(this).css('display') != 'none') tmpRow[tmpRow.length] = formatData($(this).html());
});
}
row2CSV(tmpRow);
// actual data
$(el).find('tr').each(function () {
var tmpRow = [];
$(this).filter(':visible').find('td').each(function () {
if ($(this).css('display') != 'none') tmpRow[tmpRow.length] = formatData($(this).html());
});
row2CSV(tmpRow);
});
if (options.delivery == 'popup') {
var mydata = csvData.join('\n');
return popup(mydata);
} else {
var mydata = csvData.join('\n');
return mydata;
}
function row2CSV(tmpRow) {
var tmp = tmpRow.join('') // to remove any blank rows
// alert(tmp);
if (tmpRow.length > 0 && tmp != '') {
var mystr = tmpRow.join(options.separator);
csvData[csvData.length] = mystr;
}
}
function formatData(input) {
// replace " with “
var regexp = new RegExp(/["]/g);
var output = input.replace(regexp, "“");
//HTML
var regexp = new RegExp(/\<[^\<]+\>/g);
var output = output.replace(regexp, "");
if (output == "") return '';
return '"' + output + '"';
}
function popup(data) {
var generator = window.open('', 'csv', 'height=400,width=600');
generator.document.write('<html><head><title>CSV</title>');
generator.document.write('</head><body >');
generator.document.write('<textArea cols=70 rows=15 wrap="off" >');
generator.document.write(data);
generator.document.write('</textArea>');
generator.document.write('</body></html>');
generator.document.close();
return true;
}
};
But currently when i user clicks on the link, nothing will happen. but if i move the link to be inside the main view instead of inside the partial view the script will fire. but on the main view no data will be displyed , so i want the "Export Table data into Excel" to be rendered whenever the partial view is rendered,, so can anyone adivce on this please?
try change
$(".export").on('click', function (event) {
on
$(document).on('click', ".export", function (event) {

Export JQGrid data to Excel using javascript

I want to download the grid data in csv format , by looking at the link http://jsfiddle.net/hybrid13i/JXrwM/ and using JSONToCSVConvertor($("#reportGrid").jqGrid("getGridParam", "data"),"Report",true);
you can download a csv file but its column name are variable names not label any idea how can i fix this , or there is another solution
You can use $("#reportGrid").jqGrid("getGridParam", "colNames") to get column headers.
By the way you can use jQuery.extend to make copy of the data, returned from $("#reportGrid").jqGrid("getGridParam", "data"), and then modify the data before calling of JSONToCSVConvertor.
UPDATED: The object which you get by $("#reportGrid").jqGrid("getGridParam", "data") is the reference to internal data parameters. So it contains all what it should contains. To have less properties in the items of the data you should first make a copy of the object and the modify it like you want. For example to delete Id property from all items of the data you can do the following:
var myData = $.extend(true, [],
$("#reportGrid").jqGrid("getGridParam", "data"));
$.each(myData, function () { delete this.Id; });
UPDATED: One can use SheetJS, for example, to export data to Excel. See the demo https://jsfiddle.net/OlegKi/ovq05x0c/6/, created for the issue. The corresponding code of the Export to Excel button used in the demo is the following
.jqGrid("navButtonAdd", {
caption: "",
title: "Export to Excel(.XLSX)",
onClickButton: function () {
var data = $(this).jqGrid("getGridParam", "lastSelectedData"), i, item,
dataAsArray = [
["Client", "Date", "Amount", "Tax", "Total", "Closed", "Shipped via"]
];
for (i = 0; i < data.length; i++) {
item = data[i];
dataAsArray.push([
item.name, new Date(item.invdate),
item.amount, item.tax, item.total,
item.closed, item.ship_via
]);
}
var ws_name = "SheetJS", filename = "jqGrid.xlsx";
var wb = XLSX.utils.book_new(),
ws = XLSX.utils.aoa_to_sheet(dataAsArray);
XLSX.utils.book_append_sheet(wb, ws, ws_name);
XLSX.writeFile(wb, filename);
}
});
Thanks to Oleg and the man who posted http://jsfiddle.net/hybrid13i/JXrwM/ with little enhancement in it this is my final solution
function JSONToCSVConvertor(JSONData, ReportTitle, ShowLabel,headers,excludeColumns,
fileName) {
//If JSONData is not an object then JSON.parse will parse the JSON string in an Object
var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;
var CSV = '';
//Set Report title in first row or line
CSV += ReportTitle + '\r\n\n';
//This condition will generate the Label/Header
if (ShowLabel) {
var row = "";
if(headers)
{
row = headers.join(',');
}
else
{
//This loop will extract the label from 1st index of on array
for (var index in arrData[0]) {
//Now convert each value to string and comma-seprated
row += index + ',';
}
}
row = row.slice(0, -1);
//append Label row with line break
CSV += row + '\r\n';
}
//1st loop is to extract each row
for (var i = 0; i < arrData.length; i++) {
var row = "";
//2nd loop will extract each column and convert it in string comma-seprated
for (var colName in arrData[i]) {
if(excludeColumns && excludeColumns.indexOf(colName))
continue;
row += '"' + arrData[i][colName] + '",';
}
row.slice(0, row.length - 1);
//add a line break after each row
CSV += row + '\r\n';
}
if (CSV == '') {
alert("Invalid data");
return;
}
if(!fileName)
{
//Generate a file name
fileName = "MyReport_";
//this will remove the blank-spaces from the title and replace it with an underscore
fileName += ReportTitle.replace(/ /g,"_");
}
if (navigator.appName == "Microsoft Internet Explorer") {
var oWin = window.open();
oWin.document.write('sep=,\r\n' + CSV);
oWin.document.close();
oWin.document.execCommand('SaveAs', true, fileName + ".csv");
oWin.close();
}
else
{
//Initialize file format you want csv or xls
var uri = 'data:text/csv;charset=utf-8,' + escape(CSV);
// Now the little tricky part.
// you can use either>> window.open(uri);
// but this will not work in some browsers
// or you will not get the correct file extension
//this trick will generate a temp <a /> tag
var link = document.createElement("a");
link.href = uri;
//set the visibility hidden so it will not effect on your web-layout
link.style = "visibility:hidden";
link.download = fileName + ".csv";
//this part will append the anchor tag and remove it after automatic click
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}
Usage:
JSONToCSVConvertor($(grid).jqGrid("getGridParam", "data"), $("#reportHeader").text().trim(),true,$(grid).jqGrid("getGridParam", "colNames"),["_id_"],"Report");
NOTE Please note that this solution will not work in IE

'Convert to CSV' plugin for HighCharts does not recognize all options for a chart

I am trying to convert my Highchart into a .csv file. I am using the Export chart Data to CSV plugin for the same. I have pasted the full code at the bottom of the question.
I try to run my code with the above file in scope and it does not have any effect. On further investigation I find out two things
the getOptions() method does not seem to be standard for the Highcharts library as there is no documentation for it.
It does not return the exhaustive list of options available for my Highchart. Hence, the
if (Highcharts.getOptions().exporting)
at the end of the two functions (getDataRows() and getCSV()) returns undefinedas it does not recognize exporting. What seems to be the problem here?
/**
* A small plugin for getting the CSV of a rendered chart
*/
/*global Highcharts, document */
(function (Highcharts) {
'use strict';
var each = Highcharts.each,
downloadAttrSupported = document.createElement('a').download !== undefined;
/**
* Get the data rows as a two dimensional array
*/
Highcharts.Chart.prototype.getDataRows = function () {
var csv,
options = (this.options.exporting || {}).csv || {},
xAxis = this.xAxis[0],
rows = {},
rowArr = [],
dataRows,
names = [],
i,
x,
// Options
dateFormat = options.dateFormat || '%Y-%m-%d %H:%M:%S';
// Loop the series and index values
i = 0;
each(this.series, function (series) {
if (series.options.includeInCSVExport !== false) {
names.push(series.name);
each(series.points, function (point) {
if (!rows[point.x]) {
rows[point.x] = [];
}
rows[point.x].x = point.x;
// Pies, funnels etc. use point name in X row
if (!series.xAxis) {
rows[point.x].name = point.name;
}
rows[point.x][i] = point.y;
});
i += 1;
}
});
// Make a sortable array
for (x in rows) {
if (rows.hasOwnProperty(x)) {
rowArr.push(rows[x]);
}
}
// Sort it by X values
rowArr.sort(function (a, b) {
return a.x - b.x;
});
// Add header row
dataRows = [[xAxis.isDatetimeAxis ? 'DateTime' : 'Category'].concat(names)];
// Transform the rows to CSV
each(rowArr, function (row, i) {
// Add the X/date/category
row.unshift(row.name || (xAxis.isDatetimeAxis ? Highcharts.dateFormat(dateFormat, row.x) : xAxis.categories ? Highcharts.pick(xAxis.categories[row.x], row.x) : row.x));
dataRows.push(row);
});
return dataRows;
};
/**
* Get a CSV string
*/
Highcharts.Chart.prototype.getCSV = function () {
var csv = '',
rows = this.getDataRows(),
options = (this.options.exporting || {}).csv || {},
itemDelimiter = options.itemDelimiter || ';', // use ';' for direct import to Excel
lineDelimiter = options.lineDelimiter || '\n'; // '\n' isn't working with the js csv data extraction
// Transform the rows to CSV
each(rows, function (row, i) {
// Add the values
csv += row.join(itemDelimiter);
// Add the line delimiter
if (i < rows.length - 1) {
csv += lineDelimiter;
}
});
return csv;
};
/**
* Build a HTML table with the data
* /
Highcharts.Chart.prototype.getTable = function () {
var html = '<table>',
rows = this.getDataRows(),
options = (this.options.exporting || {}).csv || {};
// Transform the rows to HTML
each(rows, function (row, i) {
var tag = i ? 'td' : 'th';
html += '<tr><' + tag + '>';
// Add the cells
html += row.join('</' + tag + '><' + tag + '>');
html += '</' + tag + '></tr>';
});
html += '</table>';
return html;
};
*/
// Add "Download CSV" to the exporting menu. Use download attribute if supported, else
// run a simple PHP script that returns a file. The source code for the PHP script can be viewed at
// https://raw.github.com/highslide-software/highcharts.com/master/studies/csv-export/csv.php
if (Highcharts.getOptions().exporting) {
Highcharts.getOptions().exporting.buttons.contextButton.menuItems.push({
text: Highcharts.getOptions().lang.downloadCSV || 'Download CSV',
onclick: function () {
var a;
// Download attribute supported
if (downloadAttrSupported) {
// Client side extraction
a = document.createElement('a');
a.href = 'data:attachment/csv,' + this.getCSV().replace(/\n/g, '%0A');
a.target = '_blank';
a.download = (this.title ? this.title.textStr.replace(/ /g, '-').toLowerCase() : 'chart') + '.csv';
document.body.appendChild(a);
a.click();
a.remove();
// Fall back to server side handling
} else {
Highcharts.post('http://www.highcharts.com/studies/csv-export/csv.php', {
csv: this.getCSV()
});
}
}
});
}
}(Highcharts));

Deleting a file in Google Script .setTrashed 'You do not have authorization to perform that action.'

I am trying to create a csv file from a Google spreadsheet every day or so. for some reason, I can delete files using the .setTrashed(True) and the file will delete, but i get an error saying 'You do not have authorization to perform that action. '
here is my code. any help would be appreciated.
function saveAsCSV() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheets = ss.getSheets();
// create a folder from the name of the spreadsheet
var folder = DocsList.getFolder(ss.getName().toLowerCase().replace(/ /g,'_'));
for (var i = 0 ; i < sheets.length ; i++) {
var sheet = sheets[i];
// append ".csv" extension to the sheet name
fileName = sheet.getName() + ".csv";
// convert all available sheet data to csv format
var csvFile = convertRangeToCsvFile_(fileName, sheet);
// update a file in the Docs List with the given name and the csv data
var folder = DocsList.getFolder('fitbitdata_mk3');
folder.createFile(fileName, csvFile);
deleteDocByName('Sheet1.csv');
Logger.log('deleted');
// folder.createFile(fileName, csvFile); //i put it before the delete
}
Browser.msgBox('UPDATED Files are waiting in a folder named ' + folder.getName());
}
function deleteDocByName(fileName){
var docs=DocsList.find(fileName)
for(n=0;n<docs.length;++n){
if(docs[n].getName() == fileName){
var ID = docs[n].getId()
DocsList.getFileById(ID).setTrashed(true)
}
}
}
function convertRangeToCsvFile_(csvFileName, sheet) {
// get available data range in the spreadsheet
var activeRange = sheet.getDataRange();
try {
var data = activeRange.getValues();
var csvFile = undefined;
// loop through the data in the range and build a string with the csv data
if (data.length > 1) {
var csv = "";
for (var row = 0; row < data.length; row++) {
for (var col = 0; col < data[row].length; col++) {
if (data[row][col].toString().indexOf(",") != -1) {
data[row][col] = "\"" + data[row][col] + "\"";
}
}
// join each row's columns
// add a carriage return to end of each row, except for the last one
if (row < data.length-1) {
csv += data[row].join(",") + "\r\n";
}
else {
csv += data[row];
}
}
csvFile = csv;
}
return csvFile;
}
catch(err) {
Logger.log(err);
Browser.msgBox(err);
}
}
I had the same problem. Please star the issue on the issue tracker here.
https://code.google.com/p/google-apps-script-issues/issues/detail?id=4145&colspec=Stars%20Opened%20ID%20Type%20Status%20Summary%20Component%20Owner

Categories