How to read the data from Excel sheet and print the result on console while working on protractor - protractor

I am working on AngularJs application testing framework where I am using Protractor. I want to read the data (urls, usernames, passwords) from an excel sheet. I am using the following code but it's showing me errors.
Please find the below code:
var Excel = require('exceljs');
var wrkbook = new Excel.Workbook();
wrkbook.xlsx.readFile('E:\\Login_Data.xlsx').then(function()
{
var worksheet = wrkbook.getWorksheet('Sheet1');
worksheet.eachRow(function (Row, Test_URL)
{
console.log("Row " + Test_URL + " = " + JSON.stringify(Row.User_Name));
});
});
The data from excel sheet is :
Test_URL User_Name Password
http://...com abc#1111 xyz#333
Please let me know your positive inputs so that I can run my code and proceed forward.
Thanks in advance

eachRow isn't getting the Test_URL variable that you set as function parameter; that is instead the row index.
For getting every value of the row, you can use Row.values, and also you could the value of each Cell (corresponding to that row) with .getCell.
So it should be something like this:
var Excel = require('exceljs');
var wrkbook = new Excel.Workbook();
wrkbook.xlsx.readFile('E:\\Login_Data.xlsx').then(function()
{
var worksheet = wrkbook.getWorksheet('Sheet1');
worksheet.eachRow(function (Row, rowIndex)
{
var test_url = Row.getCell(1).value;
var user_name = Row.getCell(2).value;
var password = Row.getCell(3).value;
// do whatever you want with those variables.
});
});

Related

Corrupt records from OpenXML Spreadsheet creation

I'm trying to generate a simple XLSX file using OpenXML but I'm getting an error when I open my file and the only info in the repairedRecord part of the log file is this:
Repaired Records: Cell information from /xl/worksheets/sheet1.xml part
The strange thing is that all the cells I'm trying to write do have the value I expect them to have. I'm just trying to write a single header row right now, where the headers is just an IEnumerable<string>:
using (var doc = SpreadsheetDocument.Create(filename, SpreadsheetDocumentType.Workbook)) {
var workbookPart = doc.AddWorkbookPart();
workbookPart.Workbook = new Workbook();
var worksheetPart = workbookPart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet();
var sheets = workbookPart.Workbook.AppendChild(new Sheets());
var sheet = new Sheet {
Id = workbookPart.GetIdOfPart(worksheetPart),
SheetId = 1,
Name = "Sheet 1"
};
sheets.Append(sheet);
workbookPart.Workbook.Save();
var sheetData = worksheetPart.Worksheet.AppendChild(new SheetData());
var row = new Row { RowIndex = 1 };
var column = 1;
foreach (var header in headers)
row.AppendChild(new Cell {
CellReference = GetColumnLetter(column++) + "1",
DataType = CellValues.SharedString,
CellValue = new CellValue(header)
});
sheetData.Append(row);
workbookPart.Workbook.Save();
}
If you're inserting a string value, you should be using CellValues.InlineString
foreach (var header in headers)
row.AppendChild(new Cell (new InlineString(new Text(header))) {
CellReference = GetColumnLetter(column++) + "1",
DataType = CellValues.InlineString
});

I am working on this code to update google contacts with google forms and spreadsheet linked to it

I want this code to auto add contacts using trigger when form is submit but i get errors.
The code works properly with spreadsheet but I am not able get it work with forms.
I am kind of noob with coding.
So simple explanation would be helpful
Also contacts get add to "other" group in google contacts,is there any way to add them directly to "my contacts"?
function createHeaders() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
// Freezes the first row
sheet.setFrozenRows(1);
// Set the values we want for headers
var values = [
["First Name", "Last Name", "Email", "Phone Number", "Company", "Notes"]
];
// Set the range of cells
var range = sheet.getRange("A1:F1");
// Call the setValues method on range and pass in our values
range.setValues(values);
}
function createContact() {
var alreadyAdded = "Already added";
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2; // First row of data to process
var numRows = 2; // Number of rows to process
// Fetch the range of cells A2:G3
var dataRange = sheet.getRange(startRow, 1, numRows, 8)
// Fetch values for each row in the Range.
var data = dataRange.getValues();
for (var i = 0; i < data.length; ++i) {
var row = data[i];
var firstName = row[0]
var lastName = row[1]
var emailAddress = row[2]
var phone = row[3]
var company = row[4]
var notes = row[5]
var addedAlready = row[6];
if (addedAlready != alreadyAdded) {
// Create contact in Google Contacts
var contact = ContactsApp.createContact(firstName, lastName, emailAddress);
// Add values to new contact
contact.addCompany(company, "");
contact.addPhone(ContactsApp.Field.WORK_PHONE, phone);
contact.setNotes(notes);
sheet.getRange(startRow + i, 7).setValue(alreadyAdded);
};
};
};
I was able to reproduce the error by passing one or more empty strings as arguments to the createContact() method:
var contact = ContactsApp.createContact("", "", "");
Check the values in your data array by logging them to see if you've got any empty strings there. You can wrap the code in a try block the prevent errors from stopping program execution. Any errors will be logged in a catch block
try {
var contact = ContactsApp.createContact(a, b, c);
}
catch(error) {
Logger.log(error);
}
I see you're trying to connect your Spreadsheet to Google Form. Check the Connecting to Google Forms
Apps Script allows you to connect Google Forms with Google Sheets
through Forms and Spreadsheet services. This feature can automatically
create a Google Form based on data in a spreadsheet. Apps Script also
enables you to use triggers, such as onFormSubmit to perform a
specific action after a user responds to the form.
you might be referring to onFormSubmit.
Here's the code demo for your reference.

Script is clearing data too early, does anyone know why?

So I'm working on a project in Google Sheets, using scripting, that will eventually do the following;
Firstly, based on a name in a Cell , find the last 9 entries for that person in form responses.
It then arranges that data in a way that I need and writes it to a sheet, within my spreadsheet
The last part of the script (not my own work, but something i found here)
Script I found online
I've tried to adapt for my needs, not quite there yet. Creates a PDF, saves it in google drive then emails it.
This part requires a bit more work, as I want to specify what the PDF is called using the name and date. Also I'd like to specify where it's saved in google. Lastly the script only produces one PDF. Would like to eventually duplicate the script so I can either create 1 PDF or create them in batches. Will possibly post about these later, if I get stuck.
So anyways that is the overview.
Currently the script works and can query the data I want, write it to a sheet, save it to drive as PDF and email it to a single hard-coded email address. Awesomeness.
But I then tried to add a function called clearRanges which would clear out the template sheet before writing data. I used name ranges to define the 3 sections to clear. But since introducing it, and i've tried it in various parts of my script. I'm getting blank PDF's in my drive and by email.
It's like it's not waiting for the PDF to be created or email to be sent before clearing data. I've tried to put it at the start of my script too, but same thing. Got no idea why.
I was playing around with lock and waitlock as a possible solution, but it didn't seem to help.
If anyone can help out, I'd appreciate it.
function getAgentName() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
Browser.msgBox("Please go to the sheet called PDF Creator, in cell A2, choose the agent you wish to create a PDF for");
var sheet = ss.getSheetByName("PDF Creator");
var range = sheet.getRange("A2")
var value = range.getValue();
if (value == 0) {
Browser.msgBox("You need to go to the sheet named PDF Creator and put an agent name in cell A2");
} else {
getAgentData(value);
}
}
function getAgentData(value) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sourceSheet = ss.getSheetByName("Form responses 1")
var sourceRange = sourceSheet.getDataRange();
var sourceValues = sourceRange.getValues();
var agentData = [];
var commentsData = [];
for (i = 0; i < sourceValues.length; i++) {
// Defines the data layout for PDF.
var agentName = sourceValues[i][2];
var dateTime = sourceValues[i][3];
var callType = sourceValues[i][7];
var opening = sourceValues[i][8];
var rootCause = sourceValues[i][9];
var rootFix = sourceValues[i][10];
var process = sourceValues[i][11];
var consumer = sourceValues[i][12];
var control = sourceValues[i][13];
var wrapup = sourceValues[i][14];
var dpa = sourceValues[i][15];
var score = sourceValues[i][22];
var comments = sourceValues[i][16];
var agentRow = [dateTime, callType, opening, rootCause, rootFix, process, consumer, control, wrapup, dpa, score];
var commentsRow = [dateTime, comments];
if (agentName == value && agentData.length < 9) {
agentData.push(agentRow)
commentsData.push(commentsRow)
}
}
agentData.sort(function (a, b) {
return b[0] - a[0]
});
commentsData.sort(function (a, b) {
return b[0] - a[0]
});
var destSheet = ss.getSheetByName("AgentPDF");
destSheet.getRange("A1").setValue(value + "'s Quality Score card");
var range = destSheet.getRange(6, 1, agentData.length, agentData[0].length);
range.setValues(agentData);
var commentRange = destSheet.getRange(18, 1, commentsData.length, commentsData[0].length);
commentRange.setValues(commentsData);
emailSpreadsheetAsPDF();
}
/* Send Spreadsheet in an email as PDF, automatically */
function emailSpreadsheetAsPDF() {
// Send the PDF of the spreadsheet to this email address
var email = "firstname.lastname#domain.co.uk";
// Subject of email message
// The date time string can be formatted in your timezone using Utilities.formatDate method
var subject = "PDF Reports - " + (new Date()).toString();
// Get the currently active spreadsheet URL (link)
// Or use SpreadsheetApp.openByUrl("<<SPREADSHEET URL>>");
var ss = SpreadsheetApp.getActiveSpreadsheet();
// Email Body can be HTML too with your logo image - see ctrlq.org/html-mail
var body = "PDF generated using code at ctrlq.org from sheet " + ss.getName();
var url = ss.getUrl();
url = url.replace(/edit$/, '');
/* Specify PDF export parameters
// From: https://code.google.com/p/google-apps-script-issues/issues/detail?id=3579
exportFormat = pdf / csv / xls / xlsx
gridlines = true / false
printtitle = true (1) / false (0)
size = legal / letter/ A4
fzr (repeat frozen rows) = true / false
portrait = true (1) / false (0)
fitw (fit to page width) = true (1) / false (0)
add gid if to export a particular sheet - 0, 1, 2,..
*/
var url_ext = 'export?exportFormat=pdf&format=pdf' // export as pdf
+ '&size=a4' // paper size
+ '&portrait=1' // orientation, false for landscape
+ '&fitw=true&source=labnol' // fit to width, false for actual size
+ '&sheetnames=false&printtitle=false' // hide optional headers and footers
+ '&pagenumbers=false&gridlines=false' // hide page numbers and gridlines
+ '&fzr=false' // do not repeat row headers (frozen rows) on each page
+ '&gid=928916939'; // the sheet's Id
var token = ScriptApp.getOAuthToken();
// var sheets = ss.getSheets();
//make an empty array to hold your fetched blobs
var blobs = [];
// for (var i=0; i<sheets.length; i++) {
// Convert individual worksheets to PDF
// var response = UrlFetchApp.fetch(url + url_ext + sheets[i].getSheetId(), {
var response = UrlFetchApp.fetch(url + url_ext, {
headers: {
'Authorization': 'Bearer ' + token
}
});
//convert the response to a blob and store in our array
blobs[0] = response.getBlob().setName("Tester " + '.pdf');
// }
//create new blob that is a zip file containing our blob array
// var zipBlob = Utilities.zip(blobs).setName(ss.getName() + '.zip');
var test = DriveApp.createFile(blobs[0]);
//optional: save the file to the root folder of Google Drive
DriveApp.createFile(test);
// Define the scope
Logger.log("Storage Space used: " + DriveApp.getStorageUsed());
// If allowed to send emails, send the email with the PDF attachment
if (MailApp.getRemainingDailyQuota() > 0)
var lock = LockService.getScriptLock();
GmailApp.sendEmail(email, subject, body, {
attachments: [test]
});
lock.waitLock(20000);
lock.releaseLock();
clearRanges();
}
function clearRanges() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
ss.getRangeByName('Header').clearContent();
ss.getRangeByName('Scores').clearContent();
ss.getRangeByName('Comments').clearContent();
}
Can you try adding SpreadsheetApp.flush();
around line 60 before calling emailSpreadsheetAsPDF();
SpreadsheetApp.flush()
commentRange.setValues(commentsData);
SpreadsheetApp.flush();
emailSpreadsheetAsPDF();
I've faced a similar problem before and this worked.

Script to name form response spreadsheet based on form title in Google Drive

I need a script to be able to create the form response spreadsheet of a Google Form and name that Spreadsheet the same as the Form + (Responses) at the end of the name. I have no idea how to do this. I am guessing it has to do with the script below, but the script does not understand that "Title" is the same as a "Name". (I do not know how to append the "(Responses)" part at the end either.) Any help would be appreciated.
function myFunction() {
var form = FormApp.openById('FORM ID HERE').getTitle();
var ss = SpreadsheetApp.create(form);
form.setDestination(FormApp.DestinationType.SPREADSHEET, ss.getId());
}
I found the answer and also how to apply it to many forms in a folder. The answer is below.
function myFunction() {
var files = DriveApp.getFolderById("0B6Eeub3cEBoobnpxWXdjSWxJRm8").getFiles()
while (files.hasNext()) {
var file = files.next();
var form = FormApp.openById(file.getId());
var formName = DriveApp.getFileById(file.getId()).getName();
var ss = SpreadsheetApp.create(formName + ' (Responses)');
form.setDestination(FormApp.DestinationType.SPREADSHEET, ss.getId());
}
}

Protractor e2e testing

I am writing Protractor e2e testing .I need to Dynamically read the values from Excel .Can anyone help me out from this..
Inititally add xlsjs to node, and then try this code
var sheetNumber = 0;
//Define file Path name
var path = require('path');
var fileNamePath = path.resolve(__dirname, 'E:/excel.xls');
//NodeJs read file
var XLS;
if (typeof require !== 'undefined') {
XLS = require('E:/node/node_modules/xlsjs');
}
//Working with workbook
var workbook = XLS.readFile(fileNamePath);
var sheetNamelist = workbook.SheetNames;
var value = workbook.Sheets[sheetNamelist[sheetNumber]][cellId].v;
In the above sheet number means, in the Excel sheet your data is located in which sheet and cellId is in that sheet which shell data do you want. your data was stored in the variable value, you can use that data in any type.