Convert rows into columns with conditions - excel

I've the following excel which needs to be transposed to columns. I have tried using the built-in formula and hte pivot table but that did not help me much since the data is in a single column and I am looking for transposing to multiple columns.
Excel: (all data in single column)
ABC1
F1
D1
Sym1
ABC2
See Link2
ABC3
F3
D3
Sym3
ABC4
See Link4
ABC5
See Link5
The output should be like:
ABC Functions Description Sym See Link
ABC1 F1 D1 Sym1
ABC2 See Link1
ABC3 F3 D3 Sym3
ABC4 See Link4
ABC5 See Link5
See that when 'See Link' is present for the row data, none of the functions, descriptions and syms are present and vice versa.

So I figured this out. Used G script in googlesheet to get this right. For anyone looking for code, here's it:
function run() {
var inputSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
var outputSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Description");
var rows = new Array(new Array());
var values = inputSheet.getRange(1, 1, inputSheet.getLastRow()).getValues();
Logger.log(values.length);
var j = 0;
var endOfRow = false;
var singleRow = new Array();
for (var row in values) {
for (var col in values[row]) {
var value = values[row][col];
if(value.indexOf("F") != -1) {
singleRow[1] = value;
}
else if(value.indexOf("D") != -1) {
singleRow[2] = value;
}
else if(value.indexOf("See Link") != -1) {
singleRow[4] = value;
endOfRow = true;
}
else if(value.indexOf("Sym") != -1) {
singleRow[3] = value;
endOfRow = true;
}
else {
singleRow[0] = value;
}
}
if(endOfRow) {
rows[j] = singleRow;
j++;
endOfRow = false;
var singleRow = new Array();
}
}
for(var d=2; d < rows.length; d++) {
var singleRow = rows[d];
for(var f = 0; f < singleRow.length; f++) {
if(singleRow[f] == undefined) {
outputSheet.getRange(d, f+1).setValue("");
} else {
outputSheet.getRange(d, f+1).setValue(singleRow[f]);
}
}
}
}

Related

Check only a range of checkboxes

I have this code with works brilliantly for me. I just need a small alteration to be able to select a range of cells as well, meaning:
Either H15-H17 or H22 or H26 in the attached image.enter image description here
the code I have is the following:
var CHECKBOX_CELLS = ["H15", "H22", "H26"];
function onEdit(e) {
var range = e.range;
var checkboxIndex = CHECKBOX_CELLS.indexOf(range.getA1Notation());
if (checkboxIndex > -1 && range.getValue() == true) {
var sheet = range.getSheet();
for (var i=0; i<CHECKBOX_CELLS.length; i++) {
if (i==checkboxIndex) continue;
sheet.getRange(CHECKBOX_CELLS[i]).setValue(false);
}
}
}

Reading values from array with objects from a function in google sheets

I am very new to excel but I have been coding for a couple of years. Now I have created a function which returns an array of objects.
function sheetnames() {
var out = new Array()
var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
for (var i=0 ; i<sheets.length ; i++){
let totalScore = sheets[i].getRange("C2").getValue();
if(i == 0 || i == 1){
continue;
}
console.log(sheets[i].getName(), totalScore);
out.push({name: sheets[i].getName(), score: totalScore});
}
return out.sort((a)=> a.totalScore);
}
I want to call this function and write Name in A1 and score in B1 and then next row Name in A2 and score in B2 and so on and so on.
I'm calling my function in excel using =sheetnames() which i got to work before when I only returned an array with strings.
Thanks!
I solved it by updating the excelsheet straigt from the code instead of calling the function from the acctual excel.
function sheetnames() {
resetStandingsSheet();
var out = new Array()
var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
for (var i=0 ; i<sheets.length ; i++){
let totalScore = sheets[i].getRange("C2").getValue();
if(i == 0 || i == 1){
continue;
}
console.log(sheets[i].getName(), totalScore);
out.push({name: sheets[i].getName(), score: totalScore});
}
var scoresAndNames = out.sort((a)=> a.totalScore);
var standingSheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[1];
standingSheet.appendRow(["Name", "Score"]);
for(var i = 0; i < scoresAndNames.length; i++){
standingSheet.appendRow([scoresAndNames[i].name, scoresAndNames[i].score + 'p']);
}
}

Concatenate or Combine Multiple Values and Retain Fonts and Colour

I am trying to concatenate or combine a few cells together and keep their individual styles.
For instance:
A1: Mr (Arial, Red, size 10)
A2: Joseph (Courier, Blue, size 20)
A3: Lion (Arial, Green, size 15)
Using the function =A1&" "&A2&" "&A3
A5: Mr Joseph Lion (Default font, default colour, default Size)
In the Concatenated cell A5, all the fonts, sizes and colours go back to default.
Is there a way to combine the values and maintain the styles.
Thank you all in advance.
You can use this function (RICHTEXTCONCAT()) to concatenate rich text from your Sheets:
function isCell(obj) {
return (typeof obj == "object" && obj.toString() == "Range" && obj.getHeight() == 1 && obj.getWidth() == 1);
}
function RICHTEXTCONCAT() {
var nargs = arguments.length;
var resultText = "";
var styles = [];
for (var i=0; i<nargs; i++) {
var arg = arguments[i];
if (isCell(arg)) {
var startPos = resultText.length;
resultText += arg.getValue();
var rtv = arg.getRichTextValue();
if (rtv) {
var runs = rtv.getRuns();
for (var j=0; j<runs.length; j++) {
styles.push({startIndex: startPos + runs[j].getStartIndex(),
endIndex: startPos + runs[j].getEndIndex(),
textStyle: runs[j].getTextStyle().copy().build()});
}
}
} else if (typeof arg == "string") {
resultText += arg;
} else {
throw new Error("Unsupported type " + typeof arg + " for argument " + (i+1) + ". Must be a cell or a string.");
}
}
var result = SpreadsheetApp.newRichTextValue().setText(resultText);
for (var i=0; i<styles.length; i++) {
if (styles[i].startIndex === styles[i].endIndex) continue;
result.setTextStyle(styles[i].startIndex,
styles[i].endIndex,
styles[i].textStyle);
}
return result.build();
}
In theory, you could use the function as a custom function, so that it could be used in a cell such as:
=RICHTEXTCONCAT(A1, " ", A2, " ", A3)
However, Sheets does not interpret rich text return values from custom functions. That means that the only option you have is to manually call a Google Apps Script function that uses setRichTextValue() in order to execute it. An example:
function myConcat() {
var sheet = SpreadsheetApp.getActive();
var range1 = sheet.getRange("A1");
var range2 = sheet.getRange("A2");
var range3 = sheet.getRange("A3");
var result = RICHTEXTCONCAT(range1, " ", range2, " ", range3);
var destinationRange = sheet.getRange("A5");
destinationRange.setRichTextValue(result);
}
If you are interested in Rich Text Value being a possible return value from a custom function, please consider filing a Feature Request into Google's Public Issue Tracker (https://issuetracker.google.com).

Get filename from url google sheet

I have a problem.
How to get the filename from the url?
enter image description here
I wouldn't normally do this since you haven't shown us what you've tried, but I'm feeling generous.
This function should work for you. (Note that you'll need to grant permissions for it to run.)
function getFileNames() {
var sheet = SpreadsheetApp.getActive().getSheetByName("Get_File_Name");
var links = sheet.getRange("A2:A").getValues();
var filenames = [];
for (var i = 0; i < links.length; i++) {
var url = links[i][0];
if (url != "") {
var filename = SpreadsheetApp.openByUrl(links[i][0]).getName();
filenames.push([filename]);
}
}
var startRow = 2; // print in row 2 since row 1 is the header row
var fileNameColumn = 2; // Column B = column 2
var destination = sheet.getRange(startRow, fileNameColumn, filenames.length, filenames[0].length);
destination.setValues(filenames);
}
Another way
function getFileNames() {
var driveApp = DriveApp;
// SET THE SHEET HERE
var sheet = SpreadsheetApp.getActive().getSheetByName("Sheet1");
//SET THE URL LINK COLUMN HERE : From row 2 since row 1 is the header row till last row
var links = sheet.getRange("P2:P").getValues();
var filenames = [];
for (var i = 0; i < links.length; i++) {
var fileId = getIdFromUrl(links[i][0]);
if (fileId != "" && fileId != null) {
var getfile = DriveApp.getFileById(fileId);
var filename = getfile.getName();
Logger.log(filename);
filenames.push([filename]);
} else {
filenames.push([""]);
}
}
// SET STARTING ROW TO PRINT: From row 2 since row 1 is the header row
var startRow = 2;
// SET WHICH COLUMN TO PRINT : Column A = column 1 / Column B = column 2
// MAKE SURE THE SHEET LAST COLUMN HEADER IS FILLED + 1 (next column)
var fileNameColumn = sheet.getLastColumn() + 1;
var destination = sheet.getRange(startRow, fileNameColumn, filenames.length, filenames[0].length);
destination.setValues(filenames);
}
function getIdFromUrl(url) { return url.match(/[-\w]{25,}/); }
You can create a custom function in spreadsheets like this.
function getSSName(name) {
var ss = SpreadsheetApp.openByUrl(url);
return ss.getName();
}

Selenium Webdriver How to select records from table by fetching Excel Input

im struggeling for below scenario.
Application displayed records of 100 suppliers in one table have three columns namely as ID,Company name and Subscription name.
i want to take input from my excel sheet say company name"xyz" and using that input i have to click on subscription name details link so application will navigates me next page.
Sample code i have created as below:
`public static void main(String[] args) throws BiffException, IOException, Exception {
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
//Workbook location
Workbook wBook = Workbook.getWorkbook(new File("C:\Users\amit.bhagwat\Documents\TestData\SampleData.xls"));
//get sheet
jxl.Sheet Sheet = wBook.getSheet(0);
//loop
for(int i=1; i<Sheet.getRows(); i++)
{
driver.get("http://206.132.42.243/Web");
driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
driver.findElement(By.xpath("//input[#id='UserName']")).sendKeys(Sheet.getCell(0, i).getContents());
driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
driver.findElement(By.xpath("//input[#id='Password']")).sendKeys(Sheet.getCell(1, i).getContents());
driver.findElement(By.xpath("//input[#id='Password']")).sendKeys(Sheet.getCell(1, i).getContents());
Thread.sleep(40);
driver.findElement(By.xpath("//input[#name='Login']")).click();
driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
driver.findElement(By.xpath("//a[contains(text(),'Task')]")).click();
driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
driver.findElement(By.xpath("//a[contains(text(),'Data Checking')]")).click();
jxl.Sheet Sheet2 = wBook.getSheet(0);
WebElement kancheck = driver.findElement(By.name("Grant & Brown"));
kancheck.click();
System.out.println(kancheck.isSelected());
driver.findElement(By.xpath("//a[contains(text(),'Data Checking')]")).sendKeys(Sheet2.getCell(1, i).getContents());
Thread.sleep(40);` enter code here
As far as I could understand, you are trying to read the file from a remote location and then read the information from it. It would be a good practice if you can use Apache POI library to read contents at run-time.
In my project, I read all the contents from an excel sheet usingApache POI library to set the values of my variables. Here is a code snippet on how i achieved it. Hopefully this will guide you to a proper solution. :)
public void readExcelDoc() throws FileNotFoundException, IOException
{
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream("excelDoc//scripts.xls"));
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);
HSSFRow row = null;
HSSFCell cell = null;
int rows = 0; // No of rows
// rows = sheet.getPhysicalNumberOfRows();
rows = sheet.getLastRowNum();
int cols = 2; // No of columns
int tmp = 0;
// This trick ensures that we get the data properly even if it doesn't start from first few rows
for(int i = 0; i < 10 || i < rows; i++) {
row = sheet.getRow(i);
if(row != null) {
tmp = sheet.getRow(i).getPhysicalNumberOfCells();
if(tmp > cols) cols = tmp;
}
}
int testRowNo = 0;
String rowName = "Test Name";
String columnValue = " ";
//Iterate through Row and columns here. Excluding 1st row for title names
for(int r = 1; r <= rows; r++) {
row = sheet.getRow(r);
if(row != null) {
//Browse through columns using c
for(int c = 0; c < cols; c++) {
if(c==0) //Only taking data from Cell 0; Ignoring any other inputs
{
cell = row.getCell((short)c);
try
{
if(cell.getStringCellValue().contains(rowName))
{
testRowNo =row.getRowNum();
}
if(testRowNo > 0 )
{
if(cell.getColumnIndex() == 0 && row.getRowNum() > testRowNo && cell.getStringCellValue().length() !=0)
{
try{
String cellValue = cell.getStringCellValue().toLowerCase();
//System.out.println(cellValue);
scriptType.add(cellValue);
}
catch(IllegalStateException e)
{
e.printStackTrace();
scriptType.add(cell.getStringCellValue());
}
}
}
}
catch(NullPointerException e)
{
}
}
if(c==1)
{
cell = row.getCell((short)c); //this sets the column number
if(testRowNo == 0)
{
try{
String cellValue = cell.getStringCellValue();
//System.out.println(cellValue);
columnValue = cellValue;
}
catch(IllegalStateException e)
{
String cellValue = cell.toString();
columnValue = cellValue;
}
catch(NullPointerException e)
{
String cellValue = nodata;
columnValue = cellValue;
}
}
}
if(c==2)
{
cell = row.getCell((short)c); //this sets the column number
if(testRowNo == 0)
{
try{
String cellValue = cell.getStringCellValue();
//System.out.println(cellValue);
inputParameters.put(cellValue, columnValue);
}
catch(IllegalStateException e)
{
String cellValue = cell.toString();
inputParameters.put(cellValue, columnValue);
}
catch(NullPointerException e)
{
String cellValue = nodata;
inputParameters.put(cellValue, columnValue);
}
}
}
}
}
}
System.out.println("---------The parameters set from excel are : ---------");
#SuppressWarnings("rawtypes")
Iterator iterator = inputParameters.keySet().iterator();
while (iterator.hasNext()) {
String key = iterator.next().toString();
String value = inputParameters.get(key).toString();
System.out.println(key + " : " + value);
}
}

Resources