Desing Excel and open it as PDF using javascript - javascript

I have created an Excel document using javascript and I open that document but I want it to open/save as PDF not as excel document I have tried many different ways but it didn't work can anyone help.
This is the code that I use.
function exportToExcelPdf() {
input_box = confirm("Експортирај во Microsoft Excel?");
if (input_box == true) {
var xlApp = new ActiveXObject("Excel.Application");
xlApp.DisplayAlerts = false;
var xlBook = xlApp.Workbooks.Add();
xlBook.worksheets("Sheet1").activate;
var XlSheet = xlBook.activeSheet;
XlSheet.Name = "Sheet Name";
var myRange = XlSheet.Range("A1:L1");
myRange.merge();
myRange.value = "Something Some Text";
myRange.font.size = 14;
myRange.font.bold = "true";
myRange.HorizontalAlignment = -4108;
myRange.interior.colorindex = "37";
var myRange = XlSheet.Range("A3:L3");
myRange.merge();
myRange.value = "Something Some Text";
myRange.font.size = 11;
myRange.font.bold = "true";
myRange.HorizontalAlignment = -4108;
myRange.interior.colorindex = "37";
var dt = document.getElementById('<%= GridView1.ClientID %>');
for (var y = 1; y < dt.rows.length; y++)
// detailsTable is the table where the content to be exported is
{
for (var x = 0; x < dt.rows(y).cells.length; x++) {
XlSheet.Cells(y + 18, x + 1) = dt.rows(y).cells(x).innerText;
XlSheet.Cells(y + 18, x + 1).HorizontalAlignment = -4108;
}
}
//autofit the columns
XlSheet.columns.autofit;
xlApp.ActiveWindow.DisplayGridlines = false;
// Make visible:
xlApp.visible = true;
xlApp.DisplayAlerts = true;
CollectGarbage();
//xlApp.Quit();
}
}

Related

Google sheets - How to get row index of a column, based on the index of edit URL from the same row?

I am coding a room booking system using combination of Google forms and Google calendar.
When there is a new booking order:
An event will be automatically created on the selected calendar.
An edit response URL will also be generated automatically and put in column 10 of the spreadsheet in the same row where the form answer was inserted.
// This is the function to generate the edit URL (which works perfectly).
function getEditUrl(request) {
var formRes = FormApp.openById('XXXXXXXXXXXXXXXXXXXXXXXXXXXX');
var sheetRes = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('YYYYYYYYYY');
var data = sheetRes.getDataRange().getValues();
var urlCol = 10;
var responses = formRes.getResponses();
var timestamps = [],
urls = [],
resultUrls = [];
for (var i = 0; i < responses.length; i++) {
timestamps.push(responses[i].getTimestamp().setMilliseconds(0));
urls.push(responses[i].getEditResponseUrl());
}
for (var j = 1; j < data.length; j++) {
resultUrls.push([data[j][0] ? urls[timestamps.indexOf(data[j][0].setMilliseconds(0))] : '']);
}
sheetRes.getRange(2, urlCol, resultUrls.length).setValues(resultUrls);
};
However, problem occurs when there are more than 2 orders; as the next order will delete the calendar event from the previous order.
// This is the function to update the calendar event.
function updateCalendar(request) {
var sheet = SpreadsheetApp.getActiveSheet();
var lastRow = sheet.getLastRow();
var range = sheet.getRange(2, 1, lastRow, 13);
var values = range.getDisplayValues();
var calendar = CalendarApp.getCalendarById('XXXXXXXXXXXXXXXXXXXXXXXX#group.calendar.google.com');
for (var i = 0; i < responses.length; i++) {
getConflicts(request);
if (request.eventConflict == "conflict") {
sheet.getRange(lastRow, 11).setValue("conflict");
break;
} else if (request.eventConflict == "approve") {
var newEvent = calendar.createEvent("booked", request.date, request.endTime);
var newEventId = newEvent.getId().split('#')[0];
sheet.getRange(lastRow, 11).setValue("approve");
sheet.getRange(lastRow, 12).setValue(newEventId);
break;
}
}
for (var j = 1; j < values.length; j++) {
if (values[j][10] == "approve") {
var eventEditId = calendar.getEventSeriesById(values[j][11]);
eventEditId.deleteEventSeries();
sheet.getRange(j + 2, 11).setValue("");
getConflicts(request);
if (request.eventConflict == "approve" && values[j][10].length > 1) {
var newEvent = calendar.createEvent("booked", request.date, request.endTime);
var newEventId = newEvent.getId().split('#')[0];
sheet.getRange(j + 2, 11).setValue("approve");
sheet.getRange(j + 2, 12).setValue(newEventId);
break;
} else {
sheet.getRange(j + 2, 11).setValue("conflict");
break;
}
}
}
};
My questions:
How to make sure that when respondent edits his/her own response, it will always update event from the same column as the edit URL? --> I have separate function that will send edit URL to respondents
When there is more than two submission, the 3rd submission will delete event of the 2nd one. (I am sure the issue is on the updateCalendar() function).
I have been struggling so much for the past few days trying to figure out the best way to come up with best loop method. Any help / response is greatly appreciated.
EDIT:
This is the column description of the sheets (separated with |):
Timestamp
Email Address
name
Check-in date
Check-out date
Room
No. of people
total day
total
edit URL
Event Conflict
Event ID
This is the function to get event conflicts in the calendar:
function getConflicts(request){
var conflicts = request.calendar.getEvents(request.date, request.endTime);
if (conflicts.length > 0) {
request.eventConflict = "conflict";
} else {
request.eventConflict = "approve"
}
};
And this is the main function that will be triggered on formsubmit:
function main(){
var request = new Submission(lastRow);
getEndTime(request);
draftEmail(request);
updateCalendar(request);
};
This is the screenshot of the sheet
Finally I found one way to retrieve the edited row by using e.range method. So basically I created another sheet inside the same spreadsheet. When there is a new submission, it will automatically copy the new submission to the second sheet. And when there is an edited submission, it will go through the copy sheet to find the edited row, and then edit it (as well as the calendar). Credit to Tedinoz
function updateCalendarTwo(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var responsename = "AAAAAAAAAAAAAAA"
var copyname = "BBBBBBBBBBBB";
var responsesheet = ss.getSheetByName(responsename);
var copysheet = ss.getSheetByName(copyname);
var calendar = CalendarApp.getCalendarById('CCCCCCCCCCCCCCCCCCCC');
// columns on copysheet
var checkInCol = 4;
var checkOutCol = 5;
var roomNumCol = 6;
var appCol = 11
var eventIDCol = 12;
var revCol = 14;
var response = e.range;
var rRow = response.getRow()
var rLC = responsesheet.getLastColumn();
var cLC = copysheet.getLastColumn();
var rLR = responsesheet.getLastRow();
var cLR = copysheet.getLastRow();
if (rLR > cLR){
var resprange = responsesheet.getRange(rLR,1,1,rLC);
var respdata = resprange.getValues();
copysheet.appendRow(respdata[0]);
var eventTitle = copysheet.getRange(rRow,roomNumCol).getValue();
var startDate = copysheet.getRange(rRow,checkInCol).getValue();
var endDate = copysheet.getRange(rRow,checkOutCol).getValue().getTime()+ 24 * 60 * 60 * 1000;
var conflicts = calendar.getEvents(new Date(startDate), new Date(endDate));
if (conflicts.length < 1) {
var event = calendar.createAllDayEvent(eventTitle, new Date(startDate), new Date(endDate));
var eventID = event.getId().split('#')[0];
copysheet.getRange(rRow,appCol).setValue("approve");
copysheet.getRange(rRow,eventIDCol).setValue(eventID);
} else {
copysheet.getRange(rRow,appCol).setValue("conflict");
}
} else {
var resprange = responsesheet.getRange(rRow,1,1,9);
var respdata = resprange.getValues();
var copyrespRange = copysheet.getRange(rRow,1,1,9);
copyrespRange.setValues(respdata);
var respAppRange = copysheet.getRange(rRow,appCol);
var respApp = respAppRange.getValue();
if (respApp == 'conflict') {
var eventTitle = copysheet.getRange(rRow,roomNumCol).getValue();
var startDate = copysheet.getRange(rRow,checkInCol).getValue();
var endDate = copysheet.getRange(rRow,checkOutCol).getValue().getTime()+ 24 * 60 * 60 * 1000;
var conflicts = calendar.getEvents(new Date(startDate), new Date(endDate));
if (conflicts.length < 1) {
var editedEvent = calendar.createAllDayEvent(eventTitle, new Date(startDate), new Date(endDate));
var editedEventID = editedEvent.getId().split('#')[0];;
copysheet.getRange(rRow,appCol).setValue("edited");
copysheet.getRange(rRow,eventIDCol).setValue(editedEventID);
} else {
copysheet.getRange(rRow,appCol).setValue("conflict");
};
} else {
var eventEditId = copysheet.getRange(rRow,eventIDCol).getDisplayValue();
var editedEvent = calendar.getEventSeriesById(eventEditId);
editedEvent.deleteEventSeries();
var eventTitle = copysheet.getRange(rRow,roomNumCol).getValue();
var startDate = copysheet.getRange(rRow,checkInCol).getValue();
var endDate = copysheet.getRange(rRow,checkOutCol).getValue().getTime()+ 24 * 60 * 60 * 1000;
var conflicts = calendar.getEvents(new Date(startDate), new Date(endDate));
if (conflicts.length < 1) {
var editedEvent = calendar.createAllDayEvent(eventTitle, new Date(startDate), new Date(endDate));
var editedEventID = editedEvent.getId().split('#')[0];;
copysheet.getRange(rRow,appCol).setValue("edited");
copysheet.getRange(rRow,eventIDCol).setValue(editedEventID);
} else {
copysheet.getRange(rRow,appCol).setValue("conflict");
};
};
var revRange = copysheet.getRange(rRow,revCol);
var revOldValue = revRange.getValue();
if (revOldValue == null || revOldValue == ""){
revOldValue = 0;
}
var revNewValue = revOldValue+1;
revRange.setValue(revNewValue);
}
}

Javascript with localstorage check

var site = document.getElementById('display').innerHTML =
document.getElementById("site").value;
var link = document.getElementById('displayy').innerHTML =
document.getElementById("link").value;
var t = true;
var both = [site,link];
while (t == true){
var s = 0;
var y = 0;
var check = localStorage.getItem(y);
if (check === null){
localStorage.setItem(s , both);
alert(y);
break;
} else {
var s = s + 1;
var y = y + 1;
localStorage.setItem(s , both);
}
}
Javascript should check if 0 = emty if so then add it to localstorarge if no check 1 check 2 check 3 etc. I get the data from html.

Unable to click <a> tag inside a table cell and switchTo it using Selenium Webdriver JS

I am trying to get specific values from the general site that contains the annual reports of public-listed firms using Selenium Webdriver JS. Kindly help me investigate. I get the issue on clicking the Annual Report link.
The process that I'm trying to automate is listed below:
Go to site (http://edge.pse.com.ph/financialReports/form.do)
Filter by type of report (sendKeys('Annual Report') and fromDate attribute value to 4-23-2012 (year 2012 to get 4-5 annual reports of each firm)
click btnSearch
click Annual Report link per company row to view report (a tag is inside a td)
switch to the popup window
get specific values as object values and store it in the array
close popup window and get back to initial window
Repeat it on the succeeding company rows (take note that the site has pagination and a total of 22 pages (or tables) must be looped through
Kindly check my initial code for the process below. I also think that my implicitWaits are working. Does it apply on Selenium executeScript commands?
var webdriver = require('selenium-webdriver'),
By = webdriver.By,
until = webdriver.until;
var driver = new webdriver.Builder()
.forBrowser('chrome')
.build();
driver.get('http://edge.pse.com.ph/financialReports/form.do');
driver.wait(until.titleIs('Financial Reports'), 1000)
driver.manage().timeouts().implicitlyWait(5000);
driver.findElement(By.name('tmplNm')).sendKeys('Annual Report');
driver.executeScript("document.getElementsByName('fromDate').setAttribute('value', '4-23-2012')");
driver.findElement(By.id('btnSearch')).click();
var totalPages = 22;
var num = 0;
while (num < totalPages) {
var pagingArray = driver.executeScript("document.querySelector('.paging').getElementsByTagName('span')");
for (var p = 0; p < pagingArray.length; p++) {
var page = driver.executeScript("pagingArray[p].getElementsByTagName('a')[0]");
page.click();
var table = driver.executeScript("document.querySelector('table.list')");
for (var i = 0; i < table.rows.length; i++) {
for (var j = 0; j < table.rows[i].cells.length; j++) {
if (j == 1) {
// Store the current window handle
var winHandleBefore = driver.getWindowHandle();
var reportLink = driver.executeScript("table.rows[i].cells[j].getElementsByTagName('a')[0]");
reportLink.click();
// Switch to new window opened
for (var winHandle in driver.getWindowHandles()) {
driver.switchTo().window(winHandle);
}
var companyName = driver.executeScript("document.getElementById('companyName').innerHTML");
var stockTicker = driver.executeScript("document.getElementById('companyStockSymbol').innerHTML");
checkCompany(companyName, stockTicker);
var tableBS = driver.executeScript("document.getElementById('BS')");
var currentYear = driver.executeScript("tableBS.rows[1].cells[1].getElementsByTagName('span')[0]");
if (!checkBalanceSheets(companyName, currentYear)) {
bsCurrentYear = new Object();
bsCurrentYear.year = currentYear;
bsCurrentYear.currentAssets = driver.executeScript("tableBS.rows[2].cells[1].getElementsByTagName('span')[0]");
bsCurrentYear.totalAssets = driver.executeScript("tableBS.rows[3].cells[1].getElementsByTagName('span')[0]");
bsCurrentYear.currentLiabilities = driver.executeScript("tableBS.rows[4].cells[1].getElementsByTagName('span')[0]");
bsCurrentYear.totalLiabilities = driver.executeScript("tableBS.rows[5].cells[1].getElementsByTagName('span')[0]");
bsCurrentYear.company = companyName;
balanceSheets.push(bsCurrentYear);
}
var previousYear = driver.executeScript("tableBS.rows[1].cells[2].getElementsByTagName('span')[0]");
if (!checkBalanceSheets(companyName, previousYear)) {
bsPreviousYear = new Object();
bsPreviousYear.year = previousYear;
bsPreviousYear.currentAssets = driver.executeScript("tableBS.rows[2].cells[2].getElementsByTagName('span')[0]");
bsPreviousYear.totalAssets = driver.executeScript("tableBS.rows[3].cells[2].getElementsByTagName('span')[0]");
bsPreviousYear.currentLiabilities = driver.executeScript("tableBS.rows[4].cells[2].getElementsByTagName('span')[0]");
bsPreviousYear.totalLiabilities = driver.executeScript("tableBS.rows[5].cells[2].getElementsByTagName('span')[0]");
bsPreviousYear.company = companyName;
balanceSheets.push(bsPreviousYear);
}
var tableIS = driver.executeScript("document.getElementById('IS')");
if (!checkIncomeStatements(companyName, currentYear)) {
isCurrentYear = new Object();
isCurrentYear.year = currentYear;
isCurrentYear.grossrevenue = driver.executeScript("tableIS.rows[4].cells[1].getElementsByTagName('span')[0]");
isCurrentYear.grossexpense = driver.executeScript("tableIS.rows[7].cells[1].getElementsByTagName('span')[0]");
isCurrentYear.netincomeaftertax = driver.executeScript("tableIS.rows[10].cells[1].getElementsByTagName('span')[0]");
isCurrentYear.company = companyName;
isCurrentYear.eps = driver.executeScript("tableIS.rows[12].cells[1].getElementsByTagName('span')[0]");
incomeStatements.push(isCurrentYear);
}
if (!checkIncomeStatements(companyName, previousYear)) {
isPreviousYear = new Object();
isPreviousYear = previousYear;
isPreviousYear.grossrevenue = driver.executeScript("tableIS.rows[4].cells[2].getElementsByTagName('span')[0]");
isPreviousYear.grossexpense = driver.executeScript("tableIS.rows[7].cells[2].getElementsByTagName('span')[0]");
isPreviousYear.netincomeaftertax = driver.executeScript("tableIS.rows[10].cells[2].getElementsByTagName('span')[0]");
isPreviousYear.company = companyName;
isPreviousYear.eps = driver.executeScript("tableIS.rows[12].cells[2].getElementsByTagName('span')[0]");
incomeStatements.push(isPreviousYear);
}
// Close the new window, if that window no more required
driver.close();
// Switch back to original browser (first window)
driver.switchTo().window(winHandleBefore);
}
}
}
}
driver.executeScript("document.querySelector('.paging').getElementsByTagName('a')[2].click()");
num++;
}
PS CheckBalanceSheets and CheckIncomeStatements are for validating IF the year already exists and has been recorded before for the respective company
function checkCompany(name, ticker) {
var found = companies.some(function(el) {
return el.name === name;
});
if (!found) { companies.push({ name: name, ticker: ticker }); }
}
function checkBalanceSheets(name, year) {
var found = balanceSheets.some(function(el) {
return el.name === name && el.year === year;
});
}
function checkIncomeStatements(name, year) {
var found = incomeStatements.some(function(el) {
return el.name === name && el.year === year;
});
}

How do I get JavaScript to recognize whether an object is in an array?

New to JavaScript objects. In the code below, I'm able to create and populate a list of book objects that each person has "checked out". However I am unable to "return" the books because I can't get seem to identify which patron's array the book is "checked out" in. I'm using
if (object in array) . . .
I got this from one of the previous answers. The statement block with the if never executes. Thanks for your help!
function Book(title, pub_date, call_number, authors){
this.title = title;
this.availability = true;
this.pub_date = pub_date;
this.current_date = null;
this.check_out_date = null;
this.call_number = call_number;
this.authors = authors;
}
Book.prototype.checkOut = function(){
this.availability = false;
var rdom = (Math.random() * 31 +1).toFixed(0);
var current_date = new Date();
this.check_out_date = new Date(current_date - rdom*24*3600*1000);
}
Book.prototype.checkIn = function(){
this.availability = true;
}
Book.prototype.isOverdue = function(){
var current_date = new Date();
if ((current_date - this.check_out_date)/1000/3600/24 > 14)
return true;
else
return false;
}
function Author(first_name, last_name){
this.first_name = first_name;
this.last_name = last_name;
}
function Patron(firstname, lastname, lib_card){
this.firstname = firstname;
this.lastname = lastname;
this.lib_card = lib_card;
this.books_out = [];
this.fine = 0;
}
Patron.prototype.readBook = function(book){
this.books_out.push(book);
}
Patron.prototype.returnBook = function(book){
this.books_out.pop(book);
}
var redAuthors, blueAuthors, greenAuthors, yellowAuthors, purpleAuthors
var redAuthor1 = new Author('John', 'Smith');
var redAuthor2 = new Author('James', 'Sullivan');
var redAuthors = [redAuthor1, redAuthor2];
var blueAuthors = greenAuthors = yellowAuthors = purpleAuthors = redAuthors;
redBook = new Book('Lakes', 1963, 456789, redAuthors);
blueBook = new Book('Rivers', 1964, 123456, blueAuthors);
greenBook = new Book('Streams', 1965, 234567, greenAuthors);
yellowBook = new Book('Ponds', 1966, 345678, yellowAuthors);
purpleBook = new Book('Brooks', 1967, 567891, purpleAuthors);
var catalog = [redBook, blueBook, greenBook, yellowBook, purpleBook]
var patron1 = new Patron('Sally', 'Hudson', '1');
var patron2 = new Patron('Rachel', 'Hung', '2');
var patron3 = new Patron('Andy', 'Cunningham', '3');
var patron4 = new Patron('Steve', 'Cote', '4');
var patron5 = new Patron ('Ted', 'Mitrou', '5');
var patrons = [patron1, patron2, patron3, patron4, patron5]
for (var day_count = 0; day_count < 10; day_count++){
for (var book_count = 0; book_count < 5; book_count++){
if (catalog[book_count].availability == true){
for (var pat_count = 0; pat_count < 5; pat_count++){
if (patrons[pat_count].books_out.length <= 1){
catalog[book_count].checkOut();
patrons[pat_count].readBook(catalog[book_count]);
break;
}
else
continue;
}
}
else {
catalog[book_count].checkIn();
for (pat_counter = 0; pat_counter < 5; pat_counter++){
if (catalog[book_count] in patrons[pat_counter].books_out){
if (catalog[book_count].isOverdue)
patrons[pat_counter].fine += 5;
patrons[pat_counter].books_out.returnBook(catalog[book_count]);
}
}
}
}
}
for (var k = 0; k < 5; k++){
console.log("Patron: " + patrons[k].firstname + " " + patrons[k].lastname);
console.log("Books checked out: ")
for (l = 0; l < patrons[k].books_out.length; l++) {
console.log(patrons[k].books_out[l].title);
}
console.log("Fine: $" + patrons[k].fine);
console.log();
}
You can use indexOf:
if (array.indexOf(object) > -1)
x in y would only return true if x is a string containing the name of a property on y.

Why is SetTimeout not executing?

I'm trying to write a javascript bookmark that, based on the current URL, navigates you to another page. Then after that navigation is done, it looks for a particular ID tag then navigates you again.
I have the first navigation done and working:
javascript:
(function() {
ADCURL = "PageA.aspx";
var temp = window.location.href;
var tarr = temp.split("/");
var serv = "https://" + tarr[2];
var x = document.getElementsByTagName("html")[0].dir;
if (x) {
var x = document.getElementsByTagName("link");
for (i = 0; i < x.length; i++) {
var y = x[i].attributes[2].value;
var lookingfor = "_vti_bin";
var lookingforRegExp = new RegExp(lookingfor);
if (lookingforRegExp.test(y)) {
var z = y.replace("_vti_bin/spsdisco.aspx", ADCURL);
var link = serv + z;
window.location.href = link;
}
}
} else {
DL5 = document.links;
for (lKi = 0; lKi < DL5.length; lKi++) {
map = DL5[lKi];
var lookingfor = "sites";
var lookingforRegExp = new RegExp(lookingfor);
if (lookingforRegExp.test(map)) {
var lookingfor = "_layout";
var lookingforRegExp = new RegExp(lookingfor);
if (lookingforRegExp.test(map)) {} else {
var lookingfor = "SharedDocuments";
var lookingforRegExp = new RegExp(lookingfor);
if (lookingforRegExp.test(map)) {
var n = String(map).indexOf("SharedDocuments");
var x = String(map).slice(0, n);
var link = x + ADCURL;
window.location.href = link;
}
}
}
}
}
})();
however when I try to use a SetTimeout to delay the script so I can grab the ID i need from the page I navigated to, nothing happens (for now I just have a window alert in there as a placeholder until I get the SetTimeout to work):
javascript:
(function() {
ADCURL = "PageA.aspx";
var temp = window.location.href;
var tarr = temp.split("/");
var serv = "https://" + tarr[2];
var x = document.getElementsByTagName("html")[0].dir;
if (x) {
var x = document.getElementsByTagName("link");
for (i = 0; i < x.length; i++) {
var y = x[i].attributes[2].value;
var lookingfor = "_vti_bin";
var lookingforRegExp = new RegExp(lookingfor);
if (lookingforRegExp.test(y)) {
var z = y.replace("_vti_bin/spsdisco.aspx", ADCURL);
var link = serv + z;
window.location.href = link;
}
}
} else {
DL5 = document.links;
for (lKi = 0; lKi < DL5.length; lKi++) {
map = DL5[lKi];
var lookingfor = "sites";
var lookingforRegExp = new RegExp(lookingfor);
if (lookingforRegExp.test(map)) {
var lookingfor = "_layout";
var lookingforRegExp = new RegExp(lookingfor);
if (lookingforRegExp.test(map)) {} else {
var lookingfor = "SharedDocuments";
var lookingforRegExp = new RegExp(lookingfor);
if (lookingforRegExp.test(map)) {
var n = String(map).indexOf("SharedDocuments");
var x = String(map).slice(0, n);
var link = x + ADCURL;
window.location.href = link;
}
}
}
}
}
setTimeout(function(){window.alert("yes");}, 2000);
})();
Any ideas what's going on? When using javascript in bookmarks is it not possible to do what I'm trying to do?

Categories