【问题标题】:xlsx - Write inside known cell number. Can't assign valuexlsx - 在已知单元格编号内写入。无法赋值
【发布时间】:2019-02-28 13:54:08
【问题描述】:

我正在使用包 xlsx 并尝试在循环中编写一些东西。

如果我直接写单元格号码,例如G3,它可以正常工作,但显然这样的东西不能工作:

    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 };

关于如何使用动态值作为单元格名称的任何想法?

【问题讨论】:

  • 您好,我需要动态提供值 sheet['G3'] = {t: 's' /* type: string /, v 而不是要写入的静态单元格值: '测试' }; VS sheet[G${(k+1)}] = {t: 's' / type: string */, v: 'test' };

标签: javascript arrays node.js xlsx


【解决方案1】:

sheet 数组的每一项都是

的对象
{
    t: 's', // (string) Or 'n' (num) / 'b' (bool) /'d' (date)
    v: 'someValue'
}

这是通过对单元格对象使用简单的分配运算符来修改sheet[i]

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]);
}

对于给定的 test.xlsx:

      A
---------
1 | TRUE
1 | foo
1 | baz

输出将是:

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' }

你没有在你的代码中提到什么是checkData数组,但这没关系,我只是假设它返回一个'myScore' + k

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-23
    相关资源
    最近更新 更多