Is there a way to count the number of rows in an Excel sheet with exceljs? - exceljs

I need to know the number of rows per column. In exceljs there is a way to count the columns, but not the rows apparently. https://www.npmjs.com/package/exceljs#columns

For me it works fine.
exceljs version I use at this moment is 4.3.0
const rows = worksheet.getColumn(1);
const rowsCount = rows['_worksheet']['_rows'].length;

According to doc Says its supported
rowCount The total row size of the document. Equal to the row number of the last row that has values.
Reference
https://github.com/exceljs/exceljs/issues/74

Yes, I also wish to do the same, it would certainly save the trouble. At the moment my "workaround" was to loop into the column and actually count it myself ... Something like:
for(counter = 0; counter < xlCol.length; counter++) {
if (xlCol[counter]) {
numRec++;
}
}
Not exactly the ideal way it seems. Hope to get to know a better way.

Related

How to get the size of a merged cell in Google Sheets formula

I have a spreadsheet where some columns are progressively merged to represent the balance of a period. Roughly like this:
(don't mind the actual values, these are random just to illustrate)
It is easy enough to just use simple formulas to refer to the ranges to the left when you are looking at them and know, for instance, that this week is C16:C22, next week is C23:C29 and so on. Weeks are relatively simple as they are regular, but months are a bit more complex, yet still just as doable. It is toilsome, though.
What I would really like to do though, would be to just get the size of the merged cell, for instance, if there was a way to write a formula like CELL('rows') that would tell me how many rows it occupies.
Unfortunately I've only managed to find a ROW() formula function that only tells the first row of the current (merged) cell, and a ROWS() that requires that I pass it a range, which is what I'm trying to obtain in the first place. Once I have the cell size in rows, I can infer its data range to the left and won't have to manually edit the formulae for each week and month. Even if I still need to do the merging, that will save a ton of work.
I would prefer to stick with formulae only, but if the solution lies in a script, so be it.
counting merged cells is possible only with script.
but there is an alternative... for week count you can use:
=ARRAYFORMULA(IF(A2:A="";;ISOWEEKNUM(A2:A)))
then to turn it into a count like:
=ARRAYFORMULA(IF(A2:A="";;COUNTIFS(
ISOWEEKNUM(A2:A); ISOWEEKNUM(A2:A); ROW(A2:A); "<="&ROW(A2:A))))
respectively for a month, you can do:
=ARRAYFORMULA(IF(A2:A="";;MONTH(A2:A)))
I could not get the desired results with a formula like #player0 but as an alternative, you can also try this script.
Once you run the script, it will write on column F the number of rows and the range of the merged cells from column E. You can change ranges in the script to test it with other columns that have merged cells.
function numRows(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Página1");
var range = sheet.getRange("E2:E")
if( range.isPartOfMerge() ) {
var range = range.getMergedRanges();
for (i=0; i<range.length;i++){
var numRows = range[i].getNumRows();
var ranRows = range[i].getA1Notation();
var lastRow = range[i].getLastRow();
Logger.log("Number of rows in range "+ ranRows + " is: " + numRows)
sheet.getRange("F"+lastRow).setValue("Range: "+ranRows+"\n"+ "NumRows: "+numRows)
}
}
else {
}
}
Let me know if you have any questions.

How to increase google sheets/excel cell count by one and then reorder rows

I am not familiar with google sheets or excel, so I'm not even sure if what I want to do is possible.
I have one thousand rows in a google sheets document. I need a column that has a number to represent the row. Starting at an arbitrary row (lets say row 5 in the document), That cell value needs to be 1. The next row needs that column value to be 2. Then 3, 4, 5, 6... all the way to 1000. It's not feasible to do that manually, so is there a way to automatically fill in the cells with the values I need?
This next part is what I can't figure out. I've found a few solutions to the first part, but none that work with this extra condition. After I generate these numbers, I need to reorder the rows (reordering can't be done before). The problem is that if I use some formula in google sheets, as soon as I generate the numbers then reorder the rows, the formula either breaks or recalculates the numbers, setting them back to 1, 2, 3..., when (for example) after the reorder I would expect 42, 815, 934...
Is what I want to do possible, and if so how can I accomplish this?
Besides the solution that has already been provided, you can also make use of Apps Script and write your own script in order to change the cell values.
Some methods which can be of help to you are:
getRange() - in order to retrieve the range from the sheet;
setValue() - in order to set the value of the cell/s;
Thererefore, your script will end up something similar to:
function setCellValues() {
let spreadsheet = SpreadsheetApp.openById("SS_ID");
let sheet = spreadsheet.getSheetByName("SHEET_NAME");
let startRow = "START_ROW";
let startCol = "START_COL";
for (let i = 0; i < 1000; i++) {
sheet.getRange("START_ROW" + i, "START_COL").setValue(i + 1);
}
}
As for reordering the rows, you can use Apps Script for this again or a simple SORT function.
Reference
Apps Script Sheet Class - getRange();
Apps Script Range Class - setValue();
SORT function.

How to add offset'ed individual fields in a google sheet

I am working on adding the time I spend on my habits using google sheets. If you look at this example sheet, I am keeping my individual habits in columns 3-8 (see the offsets on the first row).
To add the food related habits times (columns 5 and 6), I can use the range in offset function (see formulae in D17 below "Food").
The question is: how do I add the numbers for exercise and sleep (column offsets 4, 7, and 8)? The number of columns here could be 2, 3, or more! And they might not be consecutive.
Thanks for any pointers.
To sum entries of the rows whose columns are in the given array, I would use
=SUMPRODUCT(COUNTIF({5,8,9},COLUMN(D3:J3))*(D3:J3))
This is the formula for E18 in your spreasheet.
Since the columns might not be consecutive and there can be a variable number of them, I think it is appropriate to use an Apps Script custom function, and use the spread syntax to account for the variable number of columns.
Just open the script bound to your file, copy this function and save the project:
function HABIT_TOTALS(...habitIndexes) {
const sheet = SpreadsheetApp.getActiveSheet();
const headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
let output = [];
for (let dayIndex = 0; dayIndex < 7; dayIndex++) {
let dayValue = 0;
habitIndexes.forEach(habitIndex => {
const columnIndex = headers.indexOf(habitIndex) + 1;
const dailyHabitValue = sheet.getRange(3, columnIndex).getValue();
const dayHabitValue = sheet.getRange(4 + dayIndex, columnIndex).getValue();
dayValue = Number(dayValue) + Number(dailyHabitValue) + Number(dayHabitValue);
});
output.push([dayValue]);
}
return output;
}
Notes:
This function can be used as any in-built formula from Sheets (e.g. =HABIT_TOTALS(4,7,8)).
This function gets, as arguments, the indexes of the habits to retrieve (in this case 4, 7, 8), to be found on the first row in the sheet.
It loops through all days of the week (dayIndex), returning the total amount for each day. Because of this, there's no need to drag the formula down.
For each day, it finds the column index based on the habit index provided as an argument, and adds the values for Daily and for the current day to the total value for the day.
After retrieving the total amount for the day, this value is pushed to output, the value returned by this function.
This function could be used for the Food habits, just changing the arguments: =HABIT_TOTALS(5,6), or for any other combination.
Reference:
Custom Functions in Google Sheets
Spread syntax (...)
For the calculation concerning food you can try in cell D18
=sum(filter(filter($D$3:$I$11, regexmatch($C$3:$C$11, "Daily|"&text($C18, "ddd"))), regexmatch($D$1:$I$1&"", "5|6")))
and fill down.
The numbers at the end refer to the colum numbers you have in row 1. So in E18 (Sleep and excercise) you would have
=sum(filter(filter($D$3:$I$11, regexmatch($C$3:$C$11, "Daily|"&text($C18, "ddd"))), regexmatch($D$1:$I$1&"", "4|7|8")))
Of course, it is also possible to write the last part in a cell and then refer to that cell. That would mean you can enter in E18
=sum(filter(filter($D$3:$I$11, regexmatch($C$3:$C$11, "Daily|"&text($C18, "ddd"))), regexmatch($D$1:$I$1&"", D$17)))
and fill down AND to the right.
See if that helps?

arrayformula sum in Google spreadsheet

How do you arrayformula() a sum() such as:
=sum(A1:H1)
I need to go down 1000 rows.
Another option:
=ArrayFormula(SUMIF(IF(COLUMN(A1:H1),ROW(A1:A1000)),ROW(A1:A1000),A1:H1000))
Of the two answers that work, Jacob Jan Tuinstra and AdamL, Jacob gives a better answer. Jacob's runs faster and is easier to remember.
However, why use crazy formulas when it is much easier to use Google Sheets to the fullest?
=ARRAYFORMULA(A2:A+B2:B+C2:C+D2:D+E2:E+F2:F+G2:G+H2:H)
In the foregoing formula, you can use named ranges instead of the ranges by reference.
=ARRAYFORMULA(range1+range2+range3+range4+range5+range6+range7+range8)
As well, you can sum across rows that span sheets rather than being stuck working with columns within the same sheet.
To fix the formula to block returning zeros for blank rows, use this:
=arrayFormula(if(isNumber(A2:A),A2:A+B2:B+C2:C+D2:D+E2:E+F2:F,G2:G,H2:H))
See: See Ahab's answer on Google Forums
For a cool sum accumulation formula, see Otávio Alves Ribeiro's answer on Google Forums
This is what you are looking for:
=MMULT(A1:H1000,TRANSPOSE(ARRAYFORMULA(COLUMN(A1:H1000)^0)))
See this answer on Web Application I gave: https://webapps.stackexchange.com/a/53419/29140
Note: tried it on the new Google Spreadsheet, without succes.
with new functions in google sheets (since 20 Sep, 2022) all you need is:
=BYROW(A:H; LAMBDA(x; SUM(x)))
Summing A-H horizontal and running down for 523 lines:
=ARRAYFORMULA(iferror(mmult(A1:H523;TRANSPOSE(column(A1:H1))^0)))
if I look at this formula I really think the following might be simpler. Add this to Tools > Script Editor:
function row_sum(range_to_sum_per_row) {
var result_column = [];
for (var r = 0; r < range_to_sum_per_row.length; r++) {
var row_sum = parseFloat(0);
for (var c = 0; c < range_to_sum_per_row[r].length; c++) {
row_sum += range_to_sum_per_row[r][c] || 0;
}
result_column.push([row_sum]);
}
return result_column;
}
use this like so for performance reasons, where C:H is the range you want to sum up and A:A is a column that does not contain an empty string:
=row_sum(filter(C2:H, len(A2:A)>0))
If you want to be able to add rows and sum to the last row for all values in A1:H, you can use:
=ArrayFormula(SUMIF(IF(COLUMN(A1:H1),ROW(A1:A)),ROW(A1:A),A1:H))
Alternatively, if you want be be able to add rows and columns to the spreadsheet and sum to the last of both this can also be done. Paste the following code into any cell and it will create a column of summed values for all cells in each row below and to the right of pasted cell:
=arrayformula(SUMIF(IF(COLUMN(indirect(concatenate(REGEXREPLACE(address(row(),column()+1),"[^[:alpha:]]", ""),VALUE(REGEXREPLACE(address(row(),column()),"[^[:digit:]]", "")),":",VALUE(REGEXREPLACE(address(row(),column()),"[^[:digit:]]", ""))))),ROW(indirect(concatenate(REGEXREPLACE(address(row(),column()+1),"[^[:alpha:]]", ""),VALUE(REGEXREPLACE(address(row(),column()),"[^[:digit:]]", "")),":",REGEXREPLACE(address(row(),column()+1),"[^[:alpha:]]", ""))))),ROW(indirect(concatenate(REGEXREPLACE(address(row(),column()+1),"[^[:alpha:]]", ""),VALUE(REGEXREPLACE(address(row(),column()),"[^[:digit:]]", "")),":",REGEXREPLACE(address(row(),column()+1),"[^[:alpha:]]", "")))),indirect(concatenate(concatenate(REGEXREPLACE(address(row(),column()+1),"[^[:alpha:]]", ""),VALUE(REGEXREPLACE(address(row(),column()),"[^[:digit:]]", "")),":"),address(rows($A:$A),columns($1:$1))))))
Using Query
=INDEX(TRANSPOSE(
QUERY(TRANSPOSE(FILTER(A2:H,A2:A<>"")),
"select sum(Col"&JOIN("), sum(Col",SEQUENCE(COUNTA(A2:A)))&")",0)
),,2)
notes:
generating query string on the fly
Using DSUM:
=ARRAYFORMULA(DSUM(
TRANSPOSE(FILTER({A2:A,A2:H},A2:A<>"")),
SEQUENCE(COUNTA(A2:A)),{IFERROR(1/0);IFERROR(1/0)}))
notes:
{IFERROR(1/0);IFERROR(1/0)} is to make zero creteria for DSUM.
{A2:A,A2:H} -- added fake column for DSUM to mimic header column.
may be able to cahnge the formula into DMAX or DAVERAGE
Answer similar to #adamL suggestion, but removing the internal if.
=ArrayFormula(
sumif(ROW(A1:A10)*COLUMN(A1:H1)^0,ROW(A1:A10),A1:A10)
)
In this case I use ROW(A1:A10) * COLUMN(A1:H1)^0 to generate the row number matriz. To understand how it works, you can test just this part in your Google sheets:
= ArrayFormula(ROW(A1:A10) * COLUMN(A1:H1)^0)
So, with your row matrix, sumif can operate for each line, is the line has the matched row number, it will be summed up.
Let us not complicate this.
Simply put parenthesis in each of the array in the range.
=arrayformula( Sum( (A1:A):(H1:H) )
This spans not only upto 1000 rows but upto infiinity.
If you really want to limit then go
=arrayformula( Sum( (A1:A1000):(H1:H1000) )

Get the last non-empty cell in a column in Google Sheets

I use the following function
=DAYS360(A2, A35)
to calculate the difference between two dates in my column. However, the column is ever expanding and I currently have to manually change 'A35' as I update my spreadsheet.
Is there a way (in Google Sheets) to find the last non-empty cell in this column and then dynamically set that parameter in the above function?
There may be a more eloquent way, but this is the way I came up with:
The function to find the last populated cell in a column is:
=INDEX( FILTER( A:A ; NOT( ISBLANK( A:A ) ) ) ; ROWS( FILTER( A:A ; NOT( ISBLANK( A:A ) ) ) ) )
So if you combine it with your current function it would look like this:
=DAYS360(A2,INDEX( FILTER( A:A ; NOT( ISBLANK( A:A ) ) ) ; ROWS( FILTER( A:A ; NOT( ISBLANK( A:A ) ) ) ) ))
To find the last non-empty cell you can use INDEX and MATCH functions like this:
=DAYS360(A2; INDEX(A:A; MATCH(99^99;A:A; 1)))
I think this is a little bit faster and easier.
If A2:A contains dates contiguously then INDEX(A2:A,COUNT(A2:A)) will return the last date. The final formula is
=DAYS360(A2,INDEX(A2:A,COUNT(A2:A)))
Although the question is already answered, there is an eloquent way to do it.
Use just the column name to denote last non-empty row of that column.
For example:
If your data is in A1:A100 and you want to be able to add some more data to column A, say it can be A1:A105 or even A1:A1234 later, you can use this range:
A1:A
So to get last non-empty value in a range, we will use 2 functions:
COUNTA
INDEX
The answer is =INDEX(B3:B,COUNTA(B3:B)).
Here is the explanation:
COUNTA(range): Returns number of values in a range, we can use this to get the count of rows.
INDEX(range, row, col): Returns the content of a cell, specified by row and column offset. If the column is omitted then the whole row is returned.
Examples:
INDEX(A1:C5,1,1) = A1
INDEX(A1:C5,1) = A1,B1,C1 # Whole row since the column is not specified
INDEX(A1:C5,1,2) = B1
INDEX(A1:C5,1,3) = C1
INDEX(A1:C5,2,1) = A2
INDEX(A1:C5,2,2) = B2
INDEX(A1:C5,2,3) = C2
INDEX(A1:C5,3,1) = A3
INDEX(A1:C5,3,2) = B3
INDEX(A1:C5,3,3) = C3
For the picture above, our range will be B3:B. So we will count how many values are there in range B3:B by COUNTA(B3:B) first. In the left side, it will produce 8 since there are 8 values while it will produce 9 in the right side. We also know that the last value is in the 1st column of the range B3:B so the col parameter of INDEX must be 1 and the row parameter should be COUNTA(B3:B).
PS: please upvote #bloodymurderlive's answer since he wrote it first, I'm just explaining it here.
My favorite is:
=INDEX(A2:A,COUNTA(A2:A),1)
So, for the OP's need:
=DAYS360(A2,INDEX(A2:A,COUNTA(A2:A),1))
If the column expanded only by contiguously added dates
as in my case - I used just MAX function to get last date.
The final formula will be:
=DAYS360(A2; MAX(A2:A))
Here's another one:
=indirect("A"&max(arrayformula(if(A:A<>"",row(A:A),""))))
With the final equation being this:
=DAYS360(A2,indirect("A"&max(arrayformula(if(A:A<>"",row(A:A),"")))))
The other equations on here work, but I like this one because it makes getting the row number easy, which I find I need to do more often. Just the row number would be like this:
=max(arrayformula(if(A:A<>"",row(A:A),"")))
I originally tried to find just this to solve a spreadsheet issue, but couldn't find anything useful that just gave the row number of the last entry, so hopefully this is helpful for someone.
Also, this has the added advantage that it works for any type of data in any order, and you can have blank rows in between rows with content, and it doesn't count cells with formulas that evaluate to "". It can also handle repeated values. All in all it's very similar to the equation that uses max((G:G<>"")*row(G:G)) on here, but makes pulling out the row number a little easier if that's what you're after.
Alternatively, if you want to put a script on your sheet you can make it easy on yourself if you plan on doing this a lot. Here's that scirpt:
function lastRow(sheet,column) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
if (column == null) {
if (sheet != null) {
var sheet = ss.getSheetByName(sheet);
} else {
var sheet = ss.getActiveSheet();
}
return sheet.getLastRow();
} else {
var sheet = ss.getSheetByName(sheet);
var lastRow = sheet.getLastRow();
var array = sheet.getRange(column + 1 + ':' + column + lastRow).getValues();
for (i=0;i<array.length;i++) {
if (array[i] != '') {
var final = i + 1;
}
}
if (final != null) {
return final;
} else {
return 0;
}
}
}
Here you can just type in the following if you want the last row on the same of the sheet that you're currently editing:
=LASTROW()
or if you want the last row of a particular column from that sheet, or of a particular column from another sheet you can do the following:
=LASTROW("Sheet1","A")
And for the last row of a particular sheet in general:
=LASTROW("Sheet1")
Then to get the actual data you can either use indirect:
=INDIRECT("A"&LASTROW())
or you can modify the above script at the last two return lines (the last two since you would have to put both the sheet and the column to get the actual value from an actual column), and replace the variable with the following:
return sheet.getRange(column + final).getValue();
and
return sheet.getRange(column + lastRow).getValue();
One benefit of this script is that you can choose if you want to include equations that evaluate to "". If no arguments are added equations evaluating to "" will be counted, but if you specify a sheet and column they will now be counted. Also, there's a lot of flexibility if you're willing to use variations of the script.
Probably overkill, but all possible.
This works for me. Get last value of the column A in Google sheet:
=index(A:A,max(row(A:A)*(A:A<>"")))
(It also skips blank rows in between if any)
This seems like the simplest solution that I've found to retrieve the last value in an ever-expanding column:
=INDEX(A:A,COUNTA(A:A),1)
For strictly finding the last non-empty cell in a column, this should work...
=LOOKUP(2^99, A2:A)
What about this formula for getting the last value:
=index(G:G;max((G:G<>"")*row(G:G)))
And this would be a final formula for your original task:
=DAYS360(G10;index(G:G;max((G:G<>"")*row(G:G))))
Suppose that your initial date is in G10.
I went a different route. Since I know I'll be adding something into a row/column one by one, I find out the last row by first counting the fields that have data. I'll demonstrate this with a column:
=COUNT(A5:A34)
So, let's say that returned 21. A5 is 4 rows down, so I need to get the 21st position from the 4th row down. I can do this using inderect, like so:
=INDIRECT("A"&COUNT(A5:A34)+4)
It's finding the amount of rows with data, and returning me a number I'm using as an index modifier.
for a row:
=ARRAYFORMULA(INDIRECT("A"&MAX(IF(A:A<>"", ROW(A:A), ))))
for a column:
=ARRAYFORMULA(INDIRECT(ADDRESS(1, MAX(IF(1:1<>"", COLUMN(1:1), )), 4)))
This will give the contents of the last cell:
=indirect("A"&max(ARRAYFORMULA(row(a:a)*--(a:a<>""))))
This will give the address of the last cell:
="A"&max(ARRAYFORMULA(row(a:a)*--(a:a<>"")))
This will give the row of the last cell:
=max(ARRAYFORMULA(row(a:a)*--(a:a<>"")))
Maybe you'd prefer a script. This script is way shorter than the huge one posted above by someone else:
Go to script editor and save this script:
function getLastRow(range){
while(range.length>0 && range[range.length-1][0]=='') range.pop();
return range.length;
}
One this is done you just need to enter this in a cell:
=getLastRow(A:A)
Calculate the difference between latest date in column A with the date in cell A2.
=MAX(A2:A)-A2
To find last nonempty row number (allowing blanks between them) I used below to search column A.
=ArrayFormula(IFNA(match(2,1/(A:A<>""))))
The way an amateur does it is "=CONCATENATE("A",COUNTUNIQUE(A1:A9999))", where A1 is the first cell in the column, and A9999 is farther down that column than I ever expect to have any entries. This resultant A# can be used with the INDIRECT function as needed.
Ben Collins is a Google sheets guru, he has many tips on his site for free and also offers courses. He has a free article on dynamic range names and I have used this as the basis for many of my projects.
https://www.benlcollins.com/formula-examples/dynamic-named-ranges/
Disclaimer, I have nothing to gain by referring Ben's site.
Here is a screenshot of one of my projects using dynamic ranges:
Cell D3 has this formula which was shown above except this is as an array formula:
=ArrayFormula(MAX(IF(L2s!A2:A1009<>"",ROW(2:1011))))
Cell D4 has this formula:
="L2s!A2:E"&D3
This may work:
=DAYS360(A2,INDEX(A2:A,COUNTA(A2:A)))
To pick the last in a column of arbitrary, non-empty values ignoring the header cell (A1):
=INDEX(A2:A,COUNT(A2:A))
With the introduction of LAMBDA and REDUCE functions we can now compute the row number in a single pass through the cells (Several of the solutions above filter the range twice.) and without relying on magic text or numeric values.
=lambda(rng,
REDUCE(0, rng, lambda(maxrow, cell, if(isblank(cell),maxrow,row(cell)) ) )
)(A:A)
which can be nicely packaged into a Named Function for usage like
=LAST_ROWNUM(A:A)
It works on columns with interspersed blanks, and multi-column ranges (because REDUCE iterates over the range in row-first), and partial columns (like A20:A), still returning the actual row number (not the offset within the range).
This can then be combined with Index to return the value
=DAYS360(A2, Index(A1, LAST_ROWNUM(A:A)))
(In truth, though, I suspect that the OPs date values are monotonic (even if with blanks in between), and that he could get away with
=DAYS360(A2, MAX(A2:A))
This solution is identified above as relying on the dates being "contiguous" - whether that means "no blanks" or "no missing dates" I'm not certain - but either stipulation is not necessary.)

Resources