Reputation: 185
I'm using the package xlsx and trying to write something in a loop.
If I write the cell number directly, like for example G3
, it works fine, but obviously something like this can't work:
const workbook = XLSX.readFile('test.ods');
const sheet_name_list = workbook.SheetNames;
const sheet = workbook.Sheets[workbook.SheetNames[0]];
(...)
let i = `G${k+1}`;
//we got a match , write the scores in the cells
sheet[i] = {t: 's' /* type: string */, v: checkData[k].location_id };
Any ideas on how I can use dynamic values for the cell name?
Upvotes: 3
Views: 647
Reputation: 8762
Every item of the sheet
array is an object of
{
t: 's', // (string) Or 'n' (num) / 'b' (bool) /'d' (date)
v: 'someValue'
}
This is modifying the sheet[i]
by using a simple assign operator to the cell object:
const XLSX = require('xlsx');
var workbook = XLSX.readFile('test.xlsx');
const sheet = workbook.Sheets[workbook.SheetNames[0]];
for (let k = 1 ; k < 4 ; k++) {
let i = `A${k+1}`;
console.log("Before update:");
console.log(sheet[i]);
console.log("After update:");
let cell = {
t: 's',
v: 'myScore' + k
}
sheet[i] = cell;
console.log(sheet[i]);
}
For a given test.xlsx of:
A
---------
1 | TRUE
1 | foo
1 | baz
The output will be:
Before update:
{ t: 'b', v: true }
After update:
{ t: 's', v: 'myScore1' }
Before update:
{ t: 's', v: 'foo' }
After update:
{ t: 's', v: 'myScore2' }
Before update:
{ t: 's', v: 'baz' }
After update:
{ t: 's', v: 'myScore3' }
You didn't mentioned in your code what is checkData
array, but it does not matter, I just assume that it returns a 'myScore' + k
.
Upvotes: 1