Exported Excel from HTML table not opening in google sheets - javascript

I had written javascript function to convert HTML table to Excel (done) but when I try to open my exported excel in google sheets it give me response something like this
what changes I need to make in my prototype JS function to resolve this issue
handleexportExcel :function(){
var self = this;
$(".monthly-payments-report-details #paymentExcelReport").unbind('click');
$(".monthly-payments-report-details #paymentExcelReport").click(function(e){
var payment_report_table_html = "<table border='2px'>";
var monthly_payment_report_table = document.getElementById('monthlyPaymentReportTable');
for(index = 0 ; index < monthly_payment_report_table.rows.length-1 ; index++)
{
payment_report_table_html += monthly_payment_report_table.rows[index].innerHTML+"</tr>";
}
payment_report_table_html += "</table>";
var anchor_html_excel = document.createElement('a');
anchor_html_excel.href = 'data:application/vnd.ms-excel' + ', ' + encodeURIComponent(payment_report_table_html);
anchor_html_excel.download = 'Payment Report_' + self.start_date + '_' + self.end_date + '.xls';
anchor_html_excel.click();
})
}

Google Sheets is showing you exactly what you exported.
Just because Excel decides to show an HTML table as a worksheet, doesn't mean the GS developers are obliged to include that functionality.
If you want to export an actual Excel file then use a different method in your js.

Related

How to pull a random row from google sheets and use it in an HTML table

I'm working on a small project where I am wanting to randomly pull one row of a google sheet, and then use that data in an HTML table.
For now, my solution has been first to use javascript to make a random number, then generate an HTML table from google sheets for just that row using this method. So, I end up with a URL for an HTML table with just header row, and a random row of data, similar to this. Then I just embed that table as an object in my HTML page. This is the gist of it:
< script >
window.onload = function() {
var albumno = Math.random() * 408;
var albumno = Math.round(albumno);
var albumurl = "https://docs.google.com/spreadsheets/d/UNIQUE-DOCUMENT-ID/gviz/tq?tqx=out:html&tq=SELECT%20B%2C%20D%2C%20E%2C%20F%2C%20G%20WHERE%20A%20MATCHES%20%27" + albumno + "%27&gid=1739065700";
document.getElementById("output").innerHTML = "ALBUM NUMBER: " + albumno + ".";
document.getElementById("albumpath").innerHTML = '<object align="middle" data="' + albumurl + '">';
};
</script>
There are two major drawbacks. First, the table cannot be (easily) formatted when embedded as an object. Second, my google sheet is a list that is added to weekly, and therefore I have to manually adjust the limits of the random value generated in my javascript.
Is there a way to do this more effectively in Javascript? Perhaps by scraping the full table, and then randomly selecting a row of data, which can be used in an proper HTML table (i.e. not embedded as an object)? Or maybe there exists a google sheets API that would help me?
UPDATE:
I have managed to write a quick function in Google Apps Script that picks the random row of data. I have figured two ways to output the data, option 1 as an array, or option 2 as HTML code for a table. Now how do I call this function in my HTML page, and make use of these data?
}
function randomalbum() {
//get spreadsheet
var ss = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/[DOCID]/edit#gid=1');
var sh = ss.getSheetByName("Pick List");
//find last album
var Fvals = sh.getRange("F:F").getValues();
var Flast = Fvals.filter(String).length;
var colnum = sh.getRange(2, 1, Flast).getValues();
var albumlast = Math.max.apply(null, colnum)-1;
//pick random row (note the row an album is in is 1 more than the album no.)
var rowrand = Math.round(Math.random()*(albumlast+1));
//extract data of interest
var albumrand = rowrand -1;
var pick = sh.getRange(rowrand, 5).getValues();
var artist = sh.getRange(rowrand, 6).getValues();
var title = sh.getRange(rowrand, 7).getValues();
//make array (option 1)
var array = [albumrand, pick, artist, title];
return array;
//make HTML string (option 2)
var HTMLString = " <table style='width:100%'>"
+ "<tr>"
+ "<th>Album No.</th>"
+ "<th>Picked By</th>"
+ "<th>Artist</th>"
+ "<th>Artist</th>"
+ "</tr>"
+ "<tr>"
+ "<td>" + albumrand + "</td>"
+ "<td>" + pick + "</td>"
+ "<td>" + artist + "</td>"
+ "<td>" + title + "</td>"
+ "</tr>"
+"</table>"
HTMLOutput = HtmlService.createHtmlOutput(HTMLString);
return HTMLOutput
}
Using a Google Sheets API without needing to run your own server: I remember following the suggestions in the following article to solve this a while ago.
https://coderwall.com/p/duapqq/use-a-google-spreadsheet-as-your-json-backend
You'll probably need another service to add CORS headers to the Google response because cors.io apparently no longer exists.
If you want to publish a web app out of the HTMLOutput returned by your function, you can do the following:
Rename your function to doGet: if you do this, Apps Script will run this function whenever a user visits the URL of the web app you are about to publish, as you can see here.
Remove the return array; in your code: the keyword return finishes current function, so the code will never return an HTMLOutput, and an array of values is not a valid object to return in this situation.
Publish the script as a web app: in your script editor, select Publish > Deploy as web app. Then select a Project version, choose under whose authorization the app should run and who should have access to it, and click Deploy. A URL will show app as Current web app URL. If you access that URL, you will see the HTML you created.
I hope this is of any help.

Eval multiple javascript variables not working

I am trying to grab some text content (HTML comments) on the page and convert it into variables. The text content will be of the format:
I have constructed some Javascript that works up to a point, but will not go past the final variable declaration "var shorturl = ..."
Javascript code below:
$(document).ready(function() {
if (document.getElementById("ajax-gallery")) {
var shortcode = '<!-- [var module="gallery"; var id="1"; var type="single"; var data="only";] -->';
shortcode = shortcode.replace("<!-- [", "");
shortcode = shortcode.replace("] -->", "");
eval('shortcode');
var shorturl = "shorturl = " + module + "/shortcode_" + type + ".php?id=" + id + "&data=" + data;
eval('shorturl')
updateGallery(shorturl, "ajax-gallery");
}
});
I would have thought this would work, but apparently not. I know that eval is frowned upon but at present I cannot find a "nicer" method.

How do I get a list of services in JavaScript using osascript?

I have been trying to create a script that will generate an XML structure of the names of all services available. It works fine in Script Editor, but it can not run from the command line. The code I have is:
ObjC.import("Cocoa");
ObjC.import("AppKit");
function run(arg) {
items = $.NSApp.servicesMenu.itemArray;
list = "<items>";
count = 0;
items.enumerateObjectsUsingBlock(function( obj, index, stop ){
list += "<item uid='Service" + count + "' arg='" + obj.title.UTF8String + "' valid='yes' autocomplete='" + obj.title.UTF8String + "'><title>" + obj.title.UTF8String + "</title><subtitle>Services Toolbox</subtitle><icon>icon.png</icon></item>";
count++;
});
list += "</items>";
return list;
}
This code will be used in an Alfred Workflow. Any ideas on how to change it?
As far as I can figure, running this in the osascript interpreter does not have a Services menu, but the Script Editor does. How can I get around this to get the list of services?
You are right, since the script is being launched via osascript, $.NSApp won't have access to the service menu.
But, with a little UI scripting, you can find all the menu items through the finder application:
function grabFirstNested(arr) {
if (arr.length <= 0 || !Array.isArray(arr[0])) {
return arr;
}
return grabFirstNested(arr[0]);
}
function run(arg) {
var sys = Application('System Events');
var servicesRef = sys.processes['Finder'].menuBars.menuBarItems.whose({
name: { _contains: 'finder'}
}, {ignorign: 'case'}).menus.menuItems.whose({
name: { _contains: 'services'}
}, {ignoring: 'case'}).menus.menuItems.name;
var services = grabFirstNested(servicesRef());
var list = "<items>";
services.forEach(function(service, index) {
list += "<item uid='Service" + index + "' arg='" + service + "' valid='yes' autocomplete='" + service + "'><title>" + service + "</title><subtitle>Services Toolbox</subtitle><icon>icon.png</icon></item>";
});
list += "</items>";
return list;
}
This script will access the Finder application through the System Events APIs, which give access to UI elements for scripting. Once it has the Finder application, it grabs the MenuItems from the "services" menu bar item.

Retrieve data from a json object with square brackets enclosing the data

I got this data that are am getting from the database using an xmlhttprequest.
[{"description":"welcome","location":"Nairobi","name":"Equity Bank","created_at":"2013-02-07 21:12:45"},{"description":"very nice job","location":"Kisumu","name":"Equity Bank","created_at":"2013-02-16 12:19:46"},{"description":"welcome all","location":"nairobi","name":"Equity Bank","created_at":"2013-02-16 13:28:26"},{"description":"Very nice","location":"Nairobi","name":"Equity Bank","created_at":"2013-07-08 01:50:11"},{"description":"bad job","location":"eldoret","name":"Safaricom","created_at":"2013-02-03 00:00:00"},{"description":"very nice job","location":"mombasa","name":"Deep Africa","created_at":"2013-02-05 00:00:00"}]
My main aim is to arrange the data in a column form as follows:
description location name created_at
The square brackets confuse me a little bit but it seems like a javascript array but i just cant parse it correctly.
You could just loop through it, and access each element. Here is an example formatting it into some HTML tables.
var data = [{"description":"welcome","location":"Nairobi","name":"Equity Bank","created_at":"2013-02-07 21:12:45"},{"description":"very nice job","location":"Kisumu","name":"Equity Bank","created_at":"2013-02-16 12:19:46"},{"description":"welcome all","location":"nairobi","name":"Equity Bank","created_at":"2013-02-16 13:28:26"},{"description":"Very nice","location":"Nairobi","name":"Equity Bank","created_at":"2013-07-08 01:50:11"},{"description":"bad job","location":"eldoret","name":"Safaricom","created_at":"2013-02-03 00:00:00"},{"description":"very nice job","location":"mombasa","name":"Deep Africa","created_at":"2013-02-05 00:00:00"}];
var results = document.getElementById('results');
htmlString = '<table><tr>';
for( a=0; a<data.length; a++) {
htmlString = htmlString + '<tr><td>' + data[a]['description'] + '</td><td>' + data[a]['location'] + '</td><td>' + data[a]['name'] + '</td><td>' + data[a]['created_at'] + '</tr>';
}
htmlString = htmlString + '</table>';
results.innerHTML = htmlString;
There's a jsfiddle at http://jsfiddle.net/R63BJ/
As If ur using a XMLHTTRequest you will get the data in responesText
var jsonData=eval('('+responseText+')');
var text="<table><tr><th>description</th><th>location</th>" +
"<th>name</th><th>created_at</th></tr>";
for(var i=0;i<jsonData.length;i++){
text+="<td>"+jsonData[i].description+"</td>";
text+="<td>"+jsonData[i].location+"</td>";
text+="<td>"+jsonData[i].name+"</td>";
text+="<td>"+jsonData[i].created_at+"</td>";
text+="</tr>";
}
text+="</table>"
document.getElementById("tag").innerHTML="";// make sure that data is not Present
document.getElementById("tag").innerHTML=text;
and In the Jsp Page:
<div id="tag"></tag>

Not all Ajax content loading on one domain

I have the domain http://whatthecatdragged.in/ forwarded (cloaked) to http://moppy.co.uk/wtcdi/
The root page (index.html) uses Ajax to load the content. At the original host (moppy.co.uk/wtcdi) the page and all content loads. However, at the domain forwarded domain (whatthecatdragged.in), some of the content does not load. Has it something to do with the way .each is used to fire off Ajax calls, as mentioned by AnthonyWJones?
I've attempted to debug this, but peculiarly turning on the Firebug console in Firefox 3.5 actually seems to make all the content load.
// Content building code:
$(function() {
// Set a few variables (no need for secrecy with Flickr API key).
var apiKey = 'myapikey';
// var tags = '';
var tagsArr = new Array();
// Get the photos of flickr user WhatTheCatDraggedIn.
// This Ajax call always seems to complete.
$.getJSON('http://api.flickr.com/services/rest/?&method=flickr.people.getPublicPhotos&api_key=' +
apiKey +
'&user_id=46206266#N05&extras=date_taken,tags&format=json&jsoncallback=?',
function(data) {
// Set some variables to ensure alldata is fecthed from second API
// call (below) before building majority of content.
var totalExpected = data.photos.total;
var totalFetched = 0;
var photohtml = '';
// For each photo, do the following:
$.each(data.photos.photo, function(i, item) {
// Set size of photo thumbnail to display.
var size = 's';
var append = '';
if (i == 0) {
// Display most recent thumbnail larger, and add a line
// break for small pics beneath it.
size = 'm';
append = '<br />'
}
//Only display thmbnails of 4 most recent catches (1 large, 3 small).
if (i <= 3) {
var photoSrc =
'http://farm' + item.farm + '.static.flickr.com/' +
item.server + '/' + item.id + '_' + item.secret + '_' +
size + '.jpg'
//Each thumbnail links to that photo's Flickr page.
var flickrPage =
'http://flickr.com/photos/' + item.owner +
'/' + item.id + '/';
// Each thumbnail has a big tooltip, with tags formatted appropriately.
var formattedTags = item.tags.replace(/\s/g, "<br />");
formattedTags = formattedTags.replace(/cat/, "cat: ");
formattedTags = formattedTags.replace(/loc/, "location: ");
formattedTags = formattedTags.replace(/victim/, "victim: ");
formattedTags = formattedTags.replace(/status/, "status: ");
formattedTags = formattedTags.replace(/floor/, " floor");
formattedTags = formattedTags.replace(/toy/, " toy");
//Append the built html to one varable for adding to page shortly
photohtml +=
'<a class="flickr-page-link" href="' +
flickrPage + '"><img src = "' +
photoSrc + '" title="' + formattedTags + '"/>' +
append + '</a>';
}
var photoID = item.id;
// Get the detailed photo information (including tags) for the photo.
// This is the call that perhaps fails or at least content
// generated after this call does not load.
$.getJSON(
'http://api.flickr.com/services/rest/?&method=flickr.photos.getInfo&api_key=' +
apiKey + '&photo_id=' + photoID +
'&format=json&jsoncallback=?',
function(data) {
if (data.photo.tags.tag != '') {
$.each(data.photo.tags.tag, function(j, item) {
// Place all tags in an aray for easier handling.
tagsArr.push(item.raw);
});
// Incrememt number of photos fetched.
totalFetched += 1;
// Have we got them all?
if (totalFetched == totalExpected)
fetchComplete();
}
});
// Builds a shedload more content once all JSON calls are completed.
function fetchComplete() {
// ### BUILD VICTIM list ###
// format a regex to match tags beginnign : "victim: "
var vicRe = /^v[a-z]+:\s([a-z\s]+)/
// Match the regex to the tags and count number of matches per tag.
var vicCounts = tagsArr.countVals(vicRe);
var victimsHtml = "";
// For each victim.
for (var i in vicCounts) {
var strippedTag = [i].toString().replace(/\W/g, "");
console.debug(strippedTag);
// Add a line of html with the type of victim and the number of victims of that type
victimsHtml +=
"<a href='http://flickr.com/photos/46206266#N05/tags/victim" +
strippedTag + "/'>" + [i] +
" (" + vicCounts[i] + ") </a><br />";
};
// Replace existing HTML with new version.
$('#types-dragged').html(victimsHtml);
// ### BUILD STATUS PIE CHART ###
// Build a theme for chart colours.
var wtcdicharttheme = {
colors: ['#C66800', '#D3C70B', '#DD3D0B', '#D30729',
'#DDA70B'
],
marker_color: '#000000',
font_color: '#000000',
background_colors: ['#ffffff', '#ffffff']
};
// Create a new chart object, include css id of canvas
// where chart will be drawn.
var g = new Bluff.Pie('status', '275x250');
// Set a theme and stuff.
g.set_theme(wtcdicharttheme);
// No title, as this exists via the raw page HTML.
g.title = '';
g.legend_font_size = "50px";
g.marker_font_size = "20px";
// Build a regex string to match tags beginning "status: ".
var statRe = /^s[a-z]+:\s([a-z\s]+)/
// Match regex to tags and return an object with tag
// names and number of occurences.
var statCounts = tagsArr.countVals(statRe);
// For each status.
for (var i in statCounts) {
// Add data to the chart
g.data([i], [statCounts[i]]);
};
// Draw the chart.
g.draw();
// ### BUILD LOCATION LIST ###
// Build a regex that matches tags beginning "loc: "
var locRe = /^l[a-z]+:\s([a-z\s]+)/
// Match regex to tags and return an object with
// tag names and number of occurences.
var locCounts = tagsArr.countVals(locRe);
var locatHtml = "";
// For each location.
for (var i in locCounts) {
var strippedTag = [i].toString().replace(/\W/g, "");
// Add a line of html with the location and the
//number of times victims found in that location.
locatHtml +=
"<a href='http://flickr.com/photos/46206266#N05/tags/loc" +
strippedTag + "/'>" + [i] + " (" +
locCounts[i] + ") <br />";
};
// Replace existing html with newly built information.
$('#locations').html(locatHtml);
// ### BUILD CAT LIST ###
// Build a regex that maches tags beginning "cat: ".
var catRe = /^c[a-z]+:\s([a-z_\s]+)/
//Match regex to find number of catches each cat has made
var catCounts = tagsArr.countVals(catRe);
// For each cat.
for (var i in catCounts) {
var strippedTag = [i].toString().replace(/\W/g, "");
// Insert number of catches to div titled "(catname)-catch"
$('#' + [i] + '-catch').html(
"<a href='http://flickr.com/photos/46206266#N05/tags/" +
strippedTag + "/'>" + catCounts[i] + "</a>");
};
}
});
// Insert total dragged onto page.
$('#total-dragged').html(data.photos.total);
// Insert photos onto page.
$('#latest-catches').html(photohtml);
// Add tooltips to the images from Flickr.
$('img').each(function() {
$(this).qtip({
style: {
name: 'wtcdin'
},
position: {
target: 'mouse',
adjust: {
x: 8,
y: 10
}
}
})
});
});
});
UPDATE 1: I contacted the domain name company, their advice was basically "don't use JavaScript". Still can't see why it would work under one domain name and not another... Could it be to do with the fact that they "forward" the domain by means of a frame?
The browser will block AJAX requests that are sent outside of the domain that the script is hosted on. This is most likely the cause of your problem from the sound of things.
EDIT: I've found the problem, you have console.debug() calls in your script. This method is defined by the Firebug Console which is why it's only working while the Console is active. Try removing any calls to console.debug() and see how it goes.

Categories