如何使用xlsx npm包写入特定的单元格 [英] How to write into a particular cell using xlsx npm package
问题描述
我必须将一个值写入我的xlsm文件中的特定单元格(例如D4单元格).我可以看到
I have to write a value to a particular cell (say the D4 cell) in my xlsm file. I can see the option of
XLSX.writeFile(workbook, 'out.xlsx');
但是我没有看到任何将值写入特定单元格的内容(需要写入的值应该传递到哪里?).或者,它不像提供的读取特定单元格值的示例那样清晰. 如果有人能为我提供一个简单的代码片段示例,我们将感到非常高兴.
But I am not seeing anything to write a value to a particular cell (where should the values which needs to be written passed?). Or, it is not as clear as the example provided to read a particular cell value. Would be glad if someone could provide me a simple example of snippet.
这是我读取特定单元格值的方式:
This is how I read a particular cell value:
if(typeof require !== 'undefined') XLSX = require('C:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\xlsx');
var workbook = XLSX.readFile('xlsm');
var first_sheet_name = workbook.SheetNames[0];
var address_of_cell = 'D5';
var worksheet = workbook.Sheets[first_sheet_name];
var desired_cell = worksheet[address_of_cell];
desired_value = (desired_cell ? desired_cell.v : undefined);
console.log('Cell Value is: '+ desired_value);
推荐答案
因此,要写入已定义工作表中的特定单元格-可以说,第一张工作表可以:
So to write to a specific cell in a defined sheet - lets say first sheet, you can do:
const XLSX = require('xlsx');
// read from a XLS file
let workbook = XLSX.readFile('test.xls');
// get first sheet
let first_sheet_name = workbook.SheetNames[0];
let worksheet = workbook.Sheets[first_sheet_name];
// read value in D4
let cell = worksheet['D4'].v;
console.log(cell)
// modify value in D4
worksheet['D4'].v = 'NEW VALUE from NODE';
// modify value if D4 is undefined / does not exists
XLSX.utils.sheet_add_aoa(worksheet, [['NEW VALUE from NODE']], {origin: 'D4'});
// write to new file
// formatting from OLD file will be lost!
XLSX.writeFile(workbook, 'test2.xls');
希望有帮助
这篇关于如何使用xlsx npm包写入特定的单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!