How to export paginated table data in CSV? - csv

I have a problem exporting the paginated table in csv file. It cannot export the whole paginated table, just only export the first paginated table data.
Below is my coding:
HTML
<button onclick="exportTableToCSV('manufacturer_brand.csv')">Export</button>
<table id="table_js" class="table table-bordered table-striped">
<thead>
<tr>
<th style="width: 10%;">Action</th>
<th style="width: 5%;">No.</th>
<th style="">Brand Name</th>
</thead>
<tfoot>
<tr>
<th style="width: 10%;">Action</th>
<th style="width: 5%;">No.</th>
<th style="">Brand Name</th>
</tr>
</tfoot>
</table>
Javascript
function downloadCSV(csv, filename) {
var csvFile;
var downloadLink;
// CSV file
csvFile = new Blob([csv], {type: "text/csv"});
// Download link
downloadLink = document.createElement("a");
// File name
downloadLink.download = filename;
// Create a link to the file
downloadLink.href = window.URL.createObjectURL(csvFile);
// Hide download link
downloadLink.style.display = "none";
// Add the link to DOM
document.body.appendChild(downloadLink);
// Click download link
downloadLink.click();
}
function exportTableToCSV(filename) {
var csv = [];
var rows = document.querySelectorAll("table tr");
for (var i = 1; i < rows.length; i++) {
var row = [], cols = rows[i].querySelectorAll("td, th");
for (var j = 1; j < cols.length; j++)
row.push(cols[j].innerText);
csv.push(row.join(","));
}
// Download CSV file
downloadCSV(csv.join("\n"), filename);
}
Export CSV file result like below, just can export first paginated page table, other paginate cannot export:
Below is my table, actually I have a total of 7 paginated pages in the table
How someone can guide me on how to export paginate table in a CSV file.

Related

Download html table when clicked on button

I am trying to download the contents in the html table. Can anyone help me download its contents when clicked on button. I tried with following code but not working.
function exportTableToCSV(filename) {
alert("I am an alert box!");
var csv = [];
var rows = document.querySelectorAll("table tr");
for (var i = 0; i < rows.length; i++) {
var row = [],
cols = rows[i].querySelectorAll("td, th");
for (var j = 0; j < cols.length; j++)
row.push(cols[j].innerText);
csv.push(row.join(","));
}
// Download CSV file
alert('Hey')
downloadCSV(csv.join("\n"), filename);
}
function downloadCSV(csv, filename) {
var csvFile;
var downloadLink;
// CSV file
csvFile = new Blob([csv], {
type: "text/csv"
});
// Download link
downloadLink = document.createElement("a");
// File name
downloadLink.download = filename;
// Create a link to the file
downloadLink.href = window.URL.createObjectURL(csvFile);
// Hide download link
downloadLink.style.display = "none";
// Add the link to DOM
document.body.appendChild(downloadLink);
// Click download link
downloadLink.click();
}
<table border=1><button onclick="exportTableToCSV(\'members.csv\');">Export HTML Table To CSV File</button>
<tr>
<th></th>
<th> sub_domain</th>
<th> nReviews</th>
<th> Ratings_e</th>
<th> Text_e</th>
<th> rn</th>
</tr>
<tr>
<td align=\ "right\"> 1</td>
<td> a1</td>
<td align=\ "right\"> 2</td>
<td> 1, 2</td>
<td> asd, dfdsf</td>
<td align="left"> 1</td>
</tr>
</table>
The filename given format is the issue.
You can replace the button code as follows.
<button onclick="exportTableToCSV('members.csv');">Export HTML Table To CSV File</button>
function exportTableToCSV(filename) {
alert("I am an alert box!");
var csv = [];
var rows = document.querySelectorAll("table tr");
for (var i = 0; i < rows.length; i++) {
var row = [],
cols = rows[i].querySelectorAll("td, th");
for (var j = 0; j < cols.length; j++)
row.push(cols[j].innerText);
csv.push(row.join(","));
}
// Download CSV file
alert('Hey')
downloadCSV(csv.join("\n"), filename);
}
function downloadCSV(csv, filename) {
var csvFile;
var downloadLink;
// CSV file
csvFile = new Blob([csv], {
type: "text/csv"
});
// Download link
downloadLink = document.createElement("a");
// File name
downloadLink.download = filename;
// Create a link to the file
downloadLink.href = window.URL.createObjectURL(csvFile);
// Hide download link
downloadLink.style.display = "none";
// Add the link to DOM
document.body.appendChild(downloadLink);
// Click download link
downloadLink.click();
}
<body>
<table border=1>
<button onclick="exportTableToCSV('members.csv');">Export HTML Table To CSV File</button>
<tr>
<th></th>
<th> sub_domain</th>
<th> nReviews</th>
<th> Ratings_e</th>
<th> Text_e</th>
<th> rn</th>
</tr>
<tr>
<td align=\ "right\"> 1</td>
<td> a1</td>
<td align=\ "right\"> 2</td>
<td> 1, 2</td>
<td> asd, dfdsf</td>
<td align="left"> 1</td>
</tr>
</table>
</body>

Rest Api: data shows on console but html table shows undefined

My post data is being displayed on the console. But the html table shows undefined
The image below shows the problem.
My Jquery Code:
$(document).ready(function(){
//Loading all posts
var loadposts=function(){
$.ajax({
url:"http://localhost:12091/api/post/",
crossdomain: true,
method:"GET",
complete:function(xmlhttp,status){
if(xmlhttp.status==200)
{
var data=xmlhttp.responseJSON;
$("#msg").html(data[0]);
console.log(data[0]);
var str='';
for (var i = 0; i < data.length; i++) {
str += "<tr>";
str += "<td>"+data[i].UserId+"</td>";
str += "<td>"+data[i].PostId+"</td>";
str += "<td>"+data[i].Post1+"</td>";
str += "<td><button class='btn btn-danger' onclick=\"deletepost("+data[i].PostId+")\">Delete</button></td>";
str += "<td><button class='btn btn-info' onclick=\"editpost()\">Edit</button></td>";
str += "</tr>";
}
$("#show__posts tbody").html(str);
}
else
{
$("#msg").html(xmlhttp.status+":"+xmlhttp.statusText);
}
}
});
}
loadposts();
});
The html table:
<div class="container">
<p id="msg"></p>
<table class="table table-striped" border="1" id="show__posts" cellspacing="0" cellpadding="0">
<thead>
<tr>
<th>User Id</th>
<th>Post Id</th>
<th>Post</th>
<th>Delete</th>
<th>Edit</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
What am I doing wrong?
Probably irrelevant but i'm using asp.net web api in the backend
JavaScript doesn't have a .length property for objects. If you want to work it out, you have to use Object.keys(data).length instead.

How to put elements of an array into html table rows and columns

I need to put each element of an array into the corresponding table column, but currently it just puts the entire array into the first column. I feel like this solution will be a simple nested for loop but I am unsure, would appreciate any help. Thanks!
index.html
<div id="PersonContainer" class="DBcontainer">
<form action='/addPerson' method="GET"></form>
<table class="center" id="personTable">
<caption>People Table</caption>
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Hooks ID</th>
<th>Soft Plastic ID</th>
<th>Rods ID</th>
<th>Number of Hooks</th>
<th>Number of Soft Plastics</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<button type="button" onclick="displayPerson()">Click Me</button>
</form>
</div>
index.html script
<script>
function displayPerson() {
// console.log('test');
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var person = xhttp.responseText;
var element = document.getElementById("personTable");
var result = JSON.parse(person).map((item) => Object.values(item));
for(i = 0; i < result.length; i++){
element.innerHTML += '<td>' + result[i] + '</td>';
}
}
};
xhttp.open("GET", "/AddPerson", true);
xhttp.send();
}
</script>
the xhttp.responseText
[{"id":1,"first_name":"Tyler","last_name":"Marlow","hooks_id":1,"sp_id":1,"rods_id":1,"num_hooks":10,"num_sp":30},{"id":2,"first_name":"Jon","last_name":"Marlow","hooks_id":2,"sp_id":1,"rods_id":1,"num_hooks":50,"num_sp":200}]
Also note that when another person is added I would like another row to be added to the table with the values in proper columns
Putting a new row onto a table in JavaScript can be done with the insertRow function and adding a cell to a row can be done with the insertCell function.
So in your code (depending on exactly what your parsed JSON looks like) in your for loop you are going to do something like:
row = element.insertRow(i); // add a new row to your table
row.insertCell(0).innerHTML =
row.insertCell(1).innerHTML =
and so on
....
But of course you'd put the insertCell line into a for loop as well.
function displayPerson() {
// console.log('test');
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var person = xhttp.responseText;
var element = document.getElementById("personTable");
var rows = ``;
JSON.parse(person).forEach(item => {
var row = `<tr>`;
row += `<td>${item.first_name}</td>`;
row += `<td>${item.last_name}</td>`;
row += `<td>${item.hooks_id}</td>`;
row += `<td>${item.sp_id}</td>`;
row += `<td>${item.rods_id}</td>`;
row += `<td>${item.num_hooks}</td>`;
row += `<td>${item.num_sp}</td>`;
row += `</tr>`;
rows += row;
});
element.innerHTML = rows;
}
};
xhttp.open("GET", "/AddPerson", true);
xhttp.send();
}
<div id="PersonContainer" class="DBcontainer">
<form action='/addPerson' method="GET">
<table class="center">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Hooks ID</th>
<th>Soft Plastic ID</th>
<th>Rods ID</th>
<th>Number of Hooks</th>
<th>Number of Soft Plastics</th>
</tr>
<thead>
<tbody id="personTable">
</tbody>
</table>
<button type="button" onclick="displayPerson()">Click Me</button>
</form>
</div>

json results only showing one thing in table

I am havign an issue where there is only one item being shown in my table (usually the most recent bug entered)
could you let me know if there is an error with my code?
Here is it
//Web service call to get the data
var getAllBugsData = $.get("https://m2052626.scm.tees.ac.uk/AST_14/Bugg.ly2/index.php/bug/GetAllBugs",
function(data)
{
var j = 0;
var myTotal = data.length ;
for(var i =0; i < data.length;i++)
{
var item = data[i];
bug_id = item.bug_id;
BugType = item.BugType;
Bugaddress = item.Bugaddress;
admin_id = item.admin_id;
status = item.status;
Description = item.description;
type = item.type;
var bugDetails = '<div class="PropDetails">Bug Id: '+bug_id+'</div><div class="PropDetails">Type of Bug: '+BugType+'</div><div class="PropDetails">Admin Number :'+admin_id+'</div><div class="PropDetails">Type Of Bug: '+type+'</div>';
$('.listAllBugs').append('<tr class="table-stroke"><td>'+bugDetails+'</td><td>Edit</tr>');
And the table code is this
<!--Data Table Goes HERE-->
<table data-role="table" data-mode="reflow" class="ui-responsive table-stroke">
<thead>
<tr>
<th width="100%">Bug Details</th>
</tr>
</thead>
<tbody class="listAllBugs">
</tbody>
</table>

angular.min.js doesn't load correctly with jquery load

I have trying to load html page in to div in another view using jquery load.
$("#sideMenuCustomerDivition").click(function (e) {
e.preventDefault();
$('#subContents').load('Main/Customer');
});
This is my html
<div class="contents" id="subContents">
</div>
<!-- CDN JavaScript Links-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<!-- end-->
I have put html table in my other view and trying to load data to that table using angular. But my table display like this
This is my javascript for loaded view
angular.module('myApp', ['smart-table']).controller('safeCtrl', ['$scope', function ($scope) {
var firstnames = ['Laurent', 'Blandine', 'Olivier', 'Max'];
var lastnames = ['Renard', 'Faivre', 'Frere', 'Eponge'];
var dates = ['1987-05-21', '1987-04-25', '1955-08-27', '1966-06-06'];
var id = 1;
function generateRandomItem(id) {
var firstname = firstnames[Math.floor(Math.random() * 3)];
var lastname = lastnames[Math.floor(Math.random() * 3)];
var birthdate = dates[Math.floor(Math.random() * 3)];
var balance = Math.floor(Math.random() * 2000);
return {
id: id,
firstName: firstname,
lastName: lastname,
birthDate: new Date(birthdate),
balance: balance
}
}
$scope.rowCollection = [];
for (id; id < 5; id++) {
$scope.rowCollection.push(generateRandomItem(id));
}
//copy the references (you could clone ie angular.copy but then have to go through a dirty checking for the matches)
$scope.displayedCollection = [].concat($scope.rowCollection);
//add to the real data holder
$scope.addRandomItem = function addRandomItem() {
$scope.rowCollection.push(generateRandomItem(id));
id++;
};
//remove to the real data holder
$scope.removeItem = function removeItem(row) {
var index = $scope.rowCollection.indexOf(row);
if (index !== -1) {
$scope.rowCollection.splice(index, 1);
}
}
}]);
and this is html
<table st-table="rowCollection" class="table table-striped">
<thead>
<tr>
<th>first name</th>
<th>last name</th>
<th>birth date</th>
<th>balance</th>
<th>email</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="row in rowCollection">
<td>{{row.firstName}}</td>
<td>{{row.lastName}}</td>
<td>{{row.birthDate}}</td>
<td>{{row.balance}}</td>
<td>{{row.email}}</td>
</tr>
</tbody>
</table>
<script src="~/Scripts/CustomerView.js"></script>