简体   繁体   中英

Excel file gets corrupted after I write into it using ExcelJS

I have a function where I need to write a value in an excel file at a specific row.

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();
},

First I read the file and find the row where the keyword is present in first column. Then I try to write "value123" in the second column of the same row. But when i execute this function, the excel file gets corrupted and I cannot open it anymore.

I faced the same issue in Ubuntu if I am modifying the file in LibreOffice. So i created a doc in google drive as suggested in https://github.com/guyonroche/exceljs/issues/35#issuecomment-283440743 . and downloaded to perform modification on excel

Below is the code worked for me.

    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 data

改性前

PostModification Excel data

PostmModification

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM