我有一个函数,我需要在特定行的excel文件中写一个值。
var Excel = require('exceljs');
setExcelData: function (sheetName, keyword, value123, callback) {
var workbook = new Excel.Workbook();
workbook.xlsx.readFile('example.xlsx').then(function () {
var worksheet = workbook.getWorksheet(sheetName);
var y = worksheet.getColumn(1).values;
for (var i = 1; i <= y.length; i++) {
var q = worksheet.getRow(i).values;
if (q[1] == keyword) {
worksheet.getRow(i).getCell(2).value = value123;
workbook.xlsx.writeFile('example.xlsx');
break;
}
}
});
callback();
},
首先,我读取该文件,并在第一列中找到关键字所在的行。然后我尝试写&#34; value123&#34;在同一行的第二列中。但是,当我执行此功能时,excel文件已损坏,我无法再打开它。
答案 0 :(得分:0)
如果我要在LibreOffice中修改文件,我在Ubuntu中也会遇到同样的问题。所以我按照建议在Google驱动器中创建了一个文档 https://github.com/guyonroche/exceljs/issues/35#issuecomment-283440743。并下载以在excel上进行修改
下面是为我工作的代码。
var Excel = require('exceljs');
async function excelOp() {
let workbook = new Excel.Workbook();
workbook = await workbook.xlsx.readFile('question_50508131.xlsx'); // replace question_50508131.xls with your file
let worksheet = workbook.getWorksheet('Inventory'); // replace solution with youe sheet name
let columnValues = worksheet.getColumn(1).values;
for (let row = 1; row <= columnValues.length; row += 1) {
var rowValues = worksheet.getRow(row).values;
if (rowValues[1] == 'Laptop') { // replace Laptop with required value
worksheet.getRow(row).getCell(2).value = 350; // replace 350 with replacable value
workbook.xlsx.writeFile('question_50508131.xlsx');
break;
}
}
}
excelOp();
PreModification Excel数据
PostModification Excel数据