Advanced usage
The following example shows how to use formulas to find out which of the two Teams (A or B) is the winning one. You will do that by comparing the average scores of players in each team.
The initial steps are the same as in the basic example. First, import HyperFormula and choose the configuration options:
import { HyperFormula } from 'hyperformula';
const options = { licenseKey: 'gpl-v3'};This time you will use the buildFromEmpty static method to
initialize the engine:
// initiate the engine with no dataconst hfInstance = HyperFormula.buildEmpty(options);Now, let’s prepare some data. The first column will be players’ IDs and the second column will be their scores. Then, you will define the formulas responsible for calculating the average scores.
// first column represents players' IDs// second column represents players' scoresconst playersA = [ ['1', '2'], ['2', '3'], ['3', '5'], ['4', '7'], ['5', '13'], ['6', '17']];
const playersB = [ ['7', '19'], ['8', '31'], ['9', '61'], ['10', '89'], ['11', '107'], ['12', '127']];
// in cell A1 a formula checks which team is the winning one// in cells A2 and A3 formulas calculate the average score of playersconst formulas = [ ['=IF(Formulas!A2>Formulas!A3,"TeamA","TeamB")'], ['=AVERAGE(TeamA!B1:B6)'], ['=AVERAGE(TeamB!B1:B6)']];Now prepare sheets and insert the data into them:
// add 'TeamA' sheetconst sheetNameA = hfInstance.addSheet('TeamA');// get the new sheet ID for further API callsconst sheetIdA = hfInstance.getSheetId(sheetNameA);// insert playersA content into targeted 'TeamA' sheethfInstance.setSheetContent(sheetIdA, playersA);
// add 'TeamB' sheetconst sheetNameB = hfInstance.addSheet('TeamB');// get the new sheet ID for further API callsconst sheetIdB = hfInstance.getSheetId(sheetNameB);// insert playersB content into targeted 'TeamB' sheethfInstance.setSheetContent(sheetIdB, playersB);
// check the content in the console outputconsole.log(hfInstance.getAllSheetsValues());After setting everything up, you can add formulas:
// add a sheet named 'Formulas'const sheetNameC = hfInstance.addSheet('Formulas');// get the new sheet ID for further API callsconst sheetIdC = hfInstance.getSheetId(sheetNameC);// add formulas to that sheethfInstance.setSheetContent(sheetIdC, formulas);Almost done! Now, you can use the getSheetValues method to get all
values including the calculated ones. Alternatively, you can use
getCellValueto get the value from a specific cell.
// get all sheet valuesconst sheetValues = hfInstance.getSheetValues(sheetIdC);
// get the simple cell address of 'A1' from that sheetconst simpleCellAddress = hfInstance.simpleCellAddressFromString('A1', sheetIdC);
// check the winning team 🎉const winningTeam = hfInstance.getCellValue(simpleCellAddress);
// print the result to the consoleconsole.log(winningTeam)Team A
| ID | Score |
|---|
Team B
| ID | Score |
|---|