We can create an array of arrays
Control flow is the order in which instructions are executed by a program
Typically, it will be sequentially
Two main cases where is not the case:
- Conditional (if/else)
- Loops
If (operation == “multiply”) {
x * y;
} else {
x*y
If (x>y){
console.log(x is greater than y)
If (month => 3 && month <= 9){
if(temp<=5){
console.log(“It’s cold!”)
} else {
console.log(“It’s cold!”)
What will happen if month = 6 and temp = 35?
First if is accomplished, 6 is between 3 & 9. But not the second so nothing will happen.
Only with one condition:
If we are not in this period, do nothing, or if we are in this period and the temperature is greater than 5
do nothing, else say it’s cold.
Loops tell the program to repeat an operation many times:
let sum = 0.0
for(let i=1; i<=10; i++){
sum += i;
console.log(sum);
1+2+3+4+5+6+7+8+9+10=55
Let sum = 0.0
For(let i=1;i<=10;i++){
If (i %% 2 == 0){
Sum+= i;
2+4+6+8+10=30
Let i = 0
Let sum =0
While (sum < 10) {
Sum += i
i++
0+1+2+3+4=10
To build a function:
Function build_name(fistname,lastname){
Return firstname + “ “ + lastname;
Console.log(build_name(“Bob”,”Addams”))
Function factorial(n){
If (n==1){
Return 1
}else{
Return factorial(n-1) * n
Factorial(5)
Sería:
Factorial(4)*5
Factorial(3)*4*5
Factorial(2)*3*4*5
1*2*3*4*5
120
1- Write TS code
2- Transpile to JS
3- Run
Function add(x,y) {
Return x + y
Console.log(add(3,4))
Console.log(add(3,”4”))
En vez de hacer error en la segunda CONCATENA y da 34
TS can avoid that by checking
Function add(x:number,y:number){
Return x + y
Console.log(add(3,4))
That will give us errors.
Three primitive types
- String
- Number
- Boolean
Arrays in ts are collections of variables of SAME TYPE
Array of numbers is written as: number[]
Union types is a type formed from other types and represents values which may be any of the
constituent types.
To reduce time we can just put a new name for the combination
Type numbers = number | number[]
Three ways to declare variables in TS:
- Var a = 10 (classic way of declaring variables, different than other ways)
- Let a = 10 (let, more similar to other languages, use let)
- Const a =10 (constant)
To see if its equal two ==, so x==x true
Testing if two are NOT equal x!=y
Any Boolean can be negated with !, !false = true
Simplest type of loop can allow to repeat code multiple times
Let sum = 0
For (let i=1;i<11;i++){
Sum+=i//shorthand for sum = sum + i
Console.log(sum)
Let i=1 initialises a counter, and sets it to 1 at the beginning
I menor que once tells the loop to continue while that is true
I++ tells the loop to increment the counter I by 1 each time it executes the loop body.
Create a function that tells us if a number is divisible by another.
Function is_divisible(x: number, y: number){
Return x % y == 0
X%y remainder of the operation
To see the output don’t forget to put the output shower, console.log
Console.log(is_divisible(18,3));
Objects are variables which contain both data and code
An object is an instance of a class
A class defines what data and what code an object has
The data an object contains are called fields
The code an object contains come in the form of methods (special type of functions which can also use
the data contained in the object)
Create table in one, create chart in the second
Excel scripts allow automation of tasks in Excel
Scripts are written in typescript and can be created, edited and run with the built-in code editor
Scripts can also be created by recording your actions in excel
The automate tab allows access to both methods:
- New script opens code editor
- Record Actions records your actions
AUTOMATE TAB IN EXCEL
Excel scripts are written in Typescripts
Almost all Typescript code can be used within Excel scripts
External libraries are not supported, only built in js libraries
Office scripts include (preloaded) an excelscript library which allows you to interact with the excel
workbook.
An excel script must have a main function, with a workbook object as its argument
Function main(workbook: ExcelScript.Workbook) {
// Do things here
The following example script displays the current worksheet name:
Function main(workbook: ExcelScript.Workbook){
Let sheet = workbook.getActiveWorksheet();
Console.log(sheet.getName());
An object contains both data and code
A class is a template for creating objects
- Classes define the data and code objects contain
- Often classes also specify default values for this data
In
function main(workbook: ExcelScript.Workbook) {
// Do things here
Workbook is an object, it is an instance of the class Excel.Script.Workbook
The code an object contains comes in the form of methods
- Method is a function attached to an object
- In addition to variables explicitly passed as inputs, the method can also use the data stored in
the object
Methods are called using the syntax: object.method()
class Greeter {
//First we set up the data the objects will have
greeting: string;
// Now we define the methods. First up is a special method:
constructor(message: string = “world”) {
// This code is run when we instantiate an object of this class
this.greeting = message
//All other methods follow
greet() {
return “Hello, “ + this.greeting; // the data is accessed in this form
Let greeter = new Greeter(“class”);
Console.log(greeter.greet())
Now it should say “Hello class” because what is changing is the message associated.
Constructor sets the value per default.
function main(workbook: ExcelScript.Workbook) {
let selectedSheet = workbook.getActiveWorksheet();
// Set range B6 on selectedSheet
selectedSheet.getRange(“B6”).setValue(“Hello World”);
A common paradigm is to use getter and setter methods.
IMPORTANTE CREO QUE ESTO ES LITERAL LO QUE HAY EN EL EXAMEN
Nueva columna con total sales:
Sesión del 12 de abril, 1:23:28
function main(workbook: ExcelScript.Workbook)
// Get sheet
Let sheet = workbook.getWorksheet(“data-mock-shirt-sales”);
//Get table
Let table = workbook.addTable(sheet.getRange(“A1”).getSurroundingRegion(), true);
//Add total column
//First argument is column position, -1 is add to the end
table.addColumn(-1).setName(“Total sales”);
//Number of cols/rows
Let nc = table.getColumns().length
Let nm = nc – 5;
Let nr = table.getRowCount();
//Reset to range object (i.e. not table)
Table.convertToRange();
//Get first cell in Total sales:
Let ts_1 = sheet.getRangeByIndexes(1,nc-1,nr,1);
//Set formula
Ts_1.setFormulasR1C1(“=sum(RC[-“ + nm + “];RC[-1])”);
//Autofit
Sheet.getRangeByIndexes(0,nc-1,nr,1).getFormat().autofitColumns();
//Get table
Let table = workbook.addTable(sheet.getRange(“A1”).getSurroundingRegion(), true);
True aquí es porque hay headers.
//First argument is column position, -1 is add to the end
table.addColumn(-1).setName(“Total sales”);
Esto también se puede escribir como
table.addColumn(-1; null; ‘Total sales’);
null se refiere a que de momento queremos la columna vacía
//Number of cols/rows
Let nc = table.getColumns().length
Let nm = nc – 5;
Let nr = table.getRowCount();
Lo primero son las columnas, lo segundo es la posición -5 de las columnas para poner algo ahí, lo tercero
es el número de filas.
//Reset to range object (i.e. not table)
Table.convertToRange();
No need, just to show how
//Get first cell in Total sales:
Let ts_1 = sheet.getRangeByIndexes(1,nc-1,nr,1);
Vale, aquí lo que está pasando es que estamos seleccionando la primera celda de total sales (porque al
ser tabla solo necesitamos esa). 1 es el número de row donde queremos cogerlo, es la dos porque hay
headers pero es 1 porque es 0 index. Nc-1 es porque empezamos por la última columna, pero el
programa es 0 index así que hay que restar uno. Nr para que se aplique en todas las rows. 1 porque es
una sola columna.
//Set formula
Ts_1.setFormulasR1C1(“=sum(RC[-“ + nm + “];RC[-1])”);
Ahora la fórmula, y el autofit solo le da el tamaño apropiado.
CREATE A PIVOT TABLE
Sesión 12 de abril, 1:38:39
function main(workbook: ExcelScript.Workbook) {
//Get sheet
let sheet = workbook.getWorksheet(“data-mock-shirt-sales-2”);
//Get table
let table = workbook.addTable(sheet.getRange(“A1”).getSurroundingRegion(), true);
let nc = table.getColumns().length
let nm = nc -4;
let cols = table.getColumns()
// Add new sheet and pivot table
let newSheet = workbook.addWorksheet(“Shirt_Pivot”);
let pTable= = newSheet.addPivotTable(“Shirt Pivot”, table, “A1”);
// Add pivot fields for gender and size
pTable.addRowHierarchy(pTable.getHierarchy(“Gender”));
ptalbe.addRowHierarchy(pTable.getHierarchy(“Size”));
//Add pivot fields for monthly sales
for(let i = 0; i < nm; i++){
let name = cols[4+i].getName();
pTable.addDataHierarchy(ptable.getHierarchy(name));
//Add filter to show only S, M, L
const sizeField = pTable.getHierarchy(“Size”).getFields() [0];
sizeField.applyFilter({
manualFilter: {
selectedItems: [“S”, “M”, “L”]
});
Volvemos a la clase
Two constructs which are often used in ExcelScripts and we have not seen yet
1. Enums: Every type as a constant and you can access it, for instance all the type of charts there
are. Collections of named constants. They store all these identifiers.
(this is to add a line chart)
Function main(workbook: ExcelScript.Workbook) {
Let tbl = workbook.getTable(“Table1”);
Let chart = workbook.getWorksheet(“Enums”).addChart(
ExcelScript.ChartType.line,
Tbl.getRange()
)
}
2. Interfaces
Collection of variables, each with a given type
Interface Person {
Name : string;
Age : number
}
Function main(workbook: ExcelScript.Workbook){
Let range = workbook.getWorksheet("Interfaces").getRange("A1");
Let rangeConditionalFormat=range.addConditionalFormat(
ExcelScript.ConditionalFormatType.cellValue).getCellValue();
// Set the conditional formatting rule using an interface
Let rule: ExcelScript.ConditionalCellValueRule={
formula1:"0",
operator: ExcelScript.ConditionalCellValueOperator.greaterThanOrEqual
};
rangeConditionalFormat.setRule(rule);
// Set the format to apply when condition is true
Let format = rangeConditionalFormat.getFormat();
format.getFill().setColor("green");
format.getFont().setBold(true);
}
The question is if it is greater or equal to zero. Green and bold if that’s the case.
Then following classes via cheatsheets
1. ExcelScript.Workbook: Class rep. excel workbook
2. ExcelScript.Worksheet: Class rep individual worksheet
This first block has the first cheatsheet.
Get with the type string will return the object if it exists with the name you’ve given it.
3. ExcelScript.Range: Class rep contiguous cells
4. ExcelScript.Table: Class rep excel table
5. ExcelScript.PivotTable: Class rep Excel PivotTable
6. ExcelScript.Chart: Class rep excel chart
PARA REFERENCIAR UNA HOJA
let sheet1 = workbook.addWorksheet();
sheet1.setName(“Pivot”);
PARA PONER PIVOT TABLE
function main(workbook: ExcelScript.Workbook) {
let pt = create_pivot(workbook);
change_to_average(pt);
barChart = addBarChart(Workbook.getWorksheet(“Pivot”));
function create_pivot(workbook: ExcelScript.Workbook) {
let pt = sheet1.addPivotTable(“shirt_sales”, workbook.getWorksheet(“data-mock-shirt-sales-
2”).getRange(“A1”).getSurroundingRegion()), sheet.getRange(“A1”))
pt.addRowHierarchy(pt.getHierarchy(“Gender”));
pt.addDataHierarchy(pt.getHierarchy(“Sales-January”));
return pt
function change_to_average(pt: ExcelScript.PivotTable) {
let datas = pt.getDataHierarchies();
for(let i = 0; i < datas.length; i++){
datas[i].setSummarizeBy(ExcelScript.AggregationFunction.average);
function addBarChart(sheet1:ExcelScript.Worksheet, pt:ExcelScript.PivotTable) {
let range = sheet1.getRange(“A1”). getSurroundingRegion().getResizedRange(-1,0));
sheet1.addChart(ExcelScript.ChartType.barClustered,range);
return BarChart;
function formatChart(chart: ExcelScript.Chart) {
chart.getTitle().setText(“Average sales in January”);
chart.getLegend().setVisible(false);
chart.setLeft(
´
function main(workbook: ExcelScript.Workbook)
// Get sheet
Let sheet = workbook.getWorksheet(“data-mock-shirt-sales”);
//Get table
Let table = workbook.addTable(sheet.getRange(“A1”).getSurroundingRegion(), true);
//Add total column
//First argument is column position, -1 is add to the end
table.addColumn(-1).setName(“Total sales”);
//Number of cols/rows
Let nc = table.getColumns().length
Let nm = nc – 5;
Let nr = table.getRowCount();
//Get first cell in Total sales:
Let ts_1 = sheet.getRangeByIndexes(1,nc-1,nr,1);
//Set formula
Ts_1.setFormulasR1C1(“=sum(RC[-“ + nm + “];RC[-1])”);
//Autofit
Sheet.getRangeByIndexes(0,nc-1,nr,1).getFormat().autofitColumns();
}
PARA HACER EL CHART DE 3
Function main(workbook: ExcelScript.Workbook) {
Let data =
workbook.getWorksheet(“Diamonds”).getPivotTable(“DiamondsCutClarity”).getLayout().getRange();
Let chartTypes = [ExcelScript.ChartType.columnStacked, ExcelScript.ChartType.columnClustered,
ExcelScript.ChartType.columnStaked100];
For (let i=0; i<chartTypes.length; i++){
Let chart = workbook.getWorksheet(“Bivariate – categorical^2”).addChart
(chartTypes[i], data);
Chart.getTitle().setText(“Diamonds: cut vs. clarity”);
Chart.setLeft(48.75);
Chart.setTop(28.5+i = 300);
Chart.setWidth(350);
Chart.setHeight(250);
Let data =
workbook.getWorksheet(“Diamonds”).getPivotTable(“DiamondsCutClarity”).getLayout().getRange();
De dónde vienen los datos
Let chartTypes = [ExcelScript.ChartType.columnStacked, ExcelScript.ChartType.columnClustered,
ExcelScript.ChartType.columnStaked100];
Lo de 100 es porque es la variación percentual
GRÁFICO 4
Function main(workbook: ExcelScript.Workbook) {
timeSeries(workbook);
timeSeries2(workbook);
Function timeSeries(workbook: ExcelScript.Workbook) {
Let data = wokbook.getWorksheet(“GDP”).getTable(“gdp”).getRange();
Let chart = workbook.getWorksheet(“Bivariate – quantitative^2”).addChart(ExcelScript.ChartType.line,
data);
Chart.getSeries()[0].delete();
Chart.getTitle().setText(“GDP growth rate”);
Chart.getAxes().getCategoryAxis().setNumberFormat(“yyyy”);
Chart.getAxes().getCategoryAxis().setTickLabelPosition(ExcelScript.ChartAxisTickLabelPosition.low);
//Add trendline and format
Let rate = chart.getSeries()[0];
Let tline = rate.addChartTrendLine(ExcelScript.ChartTrendlineType.movingAverage);
Tline.setMovingAveragePeriod(4);
Tline.getFormat().getLine().setLineStyle(ExcelScript.ChartLineStyle.continuous);
Rate.getFormat().getLine().setLineStyle(ExcelScript.ChartLineStyle.dot);
Rate.getFormat().getLine().setWeight(1);
Chart.setLeft(55.5);
Chart.setTop(25.5);
Chart.setWidth(655.5);
Chart.setHeight(373.5);
EJERCICIO 4 A COMBINAR PARTE 2
Function timeSeries2(workbook: ExcelScript.Workbook) {
Let data = workbook.getWorksheet(“GDP”).getTable(“gdp”).getRange();
Let chart = workbook.getWorksheet(“Bivariate – quantitative^2”).addChart(ExcelScript.ChartType.line,
data);
Chart.getSeries()[0].setAxisGroup(ExcelScript.ChartAxisGroup.secondary);
Chart.getTitle().setText(“GDP growth rate and index”);
Chart.getAxes().getCategoryAxis().setNumberFormat(“yyyy”);
Chart.getAxes().getCategoryAxis().setTickLabelPosition(ExcelScript.ChartAxisTickLabelPosition.low);
Chart.getLegend().setVisible(false);
Chart.setLeft(755.5);
Chart.setTop(25.5);
Chart.setWidth(655.5);
Chart.setHeight(373.5);