Export DataTable to Excel unable to open file - javascript

I am trying to export DataTable into excel file (.xlsx).
In jQuery, I am removing the unwanted rows.
When I try to open the excel file, it is showing:
"Excel found unreadable content in '[filename].xlsx'. Do you want to recover the contents of this workbook? If you trust the source of this workbook, click Yes."
The error is showing as:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<recoveryLog
xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
<logFileName>error128600_02.xml</logFileName><summary>Errors were detected
in file '[filename].xlsx'</summary><removedRecords summary="Following is a
list of removed records:"><removedRecord>Removed Records: Cell information
from /xl/worksheets/sheet1.xml part</removedRecord></removedRecords>
</recoveryLog>
The exported file is opening fine in OpenOffice with removed rows.
Here is the code to remove unwanted rows:
I have 5 Columns in my DataTable and removing the unwanted rows based on columns 3,4,5
customize: function (xlsx) {
var exportData=[];
var sheet =xlsx.xl.worksheets['sheet1.xml'];
var clR = $('row', sheet);
var clR = $('row', sheet);
$('row', sheet).filter(function () {
var attr = $(this).attr('r');
if(attr>3)
{
if($(this).context.children.length===5){
var Item1= parseInt($(this).context.children[2].children[0].textContent);
var Item2= parseInt($(this).context.children[3].children[0].textContent);
var Item3= parseInt($(this).context.children[4].children[0].textContent);
if(Item1===0 && Item2 ===0 && Item3===0 ){
return true;
}
else{
exportData.push([{ key: 'A', value: $(this).context.children[0].children[0].textContent },
{ key: 'B', value: $(this).context.children[1].children[0].textContent },
{ key: 'C', value: $(this).context.children[2].children[0].textContent },
{ key: 'D', value: $(this).context.children[3].children[0].textContent },
{ key: 'E', value: $(this).context.children[4].children[0].textContent }]);
}
return false;
}
}
}).remove();
//update Row
clR.each(function () {`enter code here`
var attr = $(this).attr('r');
var ind = parseInt(attr);
if(ind>3){
$(this).remove();
}
});
// Create row before data
$('row c ', sheet).each(function () {
var attr = $(this).attr('r');
var pre = attr.substring(0, 1);
if(pre>3){
$(this).remove();
}
});
function Addrow(index,data) {
msg='<row r="'+index+'">'
for(i=0;i<data.length;i++){
var key=data[i].key;
var value=data[i].value;
msg += '<c t="inlineStr" r="' + key + index + '">';
msg += '<is>';
msg += '<t>'+value+'</t>';
msg+= '</is>';
msg+='</c>';
}
msg += '</row>';
return msg;
}
//insert
var addrows="";
exportData.each(function (item,index) {
var r1 = Addrow(index+4, item);
addrows=r1+addrows;
});
sheet.childNodes[0].childNodes[1].innerHTML = sheet.childNodes[0].childNodes[1].innerHTML+addrows;
}

Related

How do customize excel with using datatable in jQuery?

I m using DataTable (Jquery) to export excel file. But I facing on how do put extra information to export excel file. I have tried some code but it didn't meet my expectation.
My expected exported excel file is as below picture:
However my output is as below picture, my title report and address is located at middle isn't on top of report:
with using code below:
{
extend: 'excelHtml5',
title: 'Trace Report',
messageTop: 'ABC company' + 'address',
//message: "Any message for header inside the file. I am not able to put message in next row in excel file but you can use \n"+'modelID'+modelId,
render: function (data, type, full, meta) {
return 'Download'; //change the button text here
},
customize: function (xlsx) {
var sheet = xlsx.xl.worksheets['sheet1.xml'];
var numrows = 10;
// add styles for the column header, these row will be moved down
var clRow = $('row', sheet);
//$(clRow[0]).find('c').attr('s', 32);
//update Row
clRow.each(function () {
var attr = $(this).attr('r');
var ind = parseInt(attr);
ind = ind + numrows;
//ind is num of row +1
$(this).attr("r", ind);
});
// Create row before data
$('row c ', sheet).each(function (index) {
var attr = $(this).attr('r');
var pre = attr.substring(0, 1);
//pre=A,B,C..-F repeat 5 time
var ind = parseInt(attr.substring(1, attr.length));
ind = ind + numrows;
$(this).attr("r", pre + ind);
});
function addRow(index, data) {
var row = sheet.createElement('row');
row.setAttribute("r", index);
for (i = 0; i < data.length; i++) {
var key = data[i].k;
var value = data[i].v;
var c = sheet.createElement('c');
c.setAttribute("t", "inlineStr");
c.setAttribute("s", "2"); /*set specific cell style here*/
c.setAttribute("r", key + index);
var is = sheet.createElement('is');
var t = sheet.createElement('t');
var text = sheet.createTextNode(value)
t.appendChild(text);
is.appendChild(t);
c.appendChild(is);
row.appendChild(c);
debugger;
}
return row;
}
//add data to extra rows
var countryStateList = 'asd';
var agencyValue = 'asd';
var reportGroupList = 'asd';
var certNo = '3e'
var r1 = addRow(1, [{
k: 'A',
v: 'Certificate Number'
}, {
k: 'B',
v: 'Model ID:'
}, {
k: 'C',
v: 'Serial Number'
}, {
k: 'D',
v: 'Calibration Date'
}]);
var r2 = addRow(2, [{
k: 'A',
v: countryStateList
}, {
k: 'B',
v: agencyValue
}, {
k: 'C',
v: reportGroupList
}, {
k: 'D',
v: certNo
}]); //add one cell for row 1
//$('row c[r^="A"]', sheet).attr( 's', '25' );
var sheetData = sheet.getElementsByTagName('sheetData')[0];
// sheetData.insertBefore(r4,sheetData.childNodes[0]);
// sheetData.insertBefore(r3,sheetData.childNodes[0]);
sheetData.insertBefore(r2, sheetData.childNodes[0]);
sheetData.insertBefore(r1, sheetData.childNodes[0]);
}
}

Exporting Pug column & Rows to CSV

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.

How to use HTML DOM elemets in alloyui dataTable

I want to show DOM elements in alloyui dataTable. but the alloyui table does not show the DOM elements. My code is as following:
var tableData = [];
this._popupContent.innerHTML = "";
for(var key in this._info){
(function(k) {
var item = {};
item.name = k;
item.dom = document.createElement('a');
item.dom.innerHTML = key;
item.dom.addEventListener("click", function(){
//do something
console.log(k);
});
tableData.push(item);
})(key)
}
YUI().use(
'aui-datatable',
function(Y) {
var columns = [
{ key: 'name',
allowHTML: true
},
{
key: 'dom',
allowHTML: true
}
];
new Y.DataTable({
columnset: columns,
recordset: tableData
}).render('#popupContent');
}
);
can some help me?

.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) {

'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));

Categories