node.jsexcelspacecreatefile

How can I remove all the spaces in the cells of excelsheet using nodejs code


I have an excel sheet with lots of spaces in between the content in each cell. I would like to keep that cell unaffected, so I would like to create a copy of the same and remove all the spaces of cell content. Is it possible to do from a nodejs code?


Solution

  • You could do so using xlsx package from npm.

    copy the File via node

    const fs = require('fs');
    fs.copyFile('source.xlsx', 'newFile.xlsx', (err) => {
        if (err) throw err;
    });
    

    read the File to any Format you like with xlsx (code simplified):

    XLSX = require('xlsx');
    workbook = XLSX.read('newFile.xlsx', {type: 'binary'});
    let worksheet = workbook.Sheets[workbook.SheetNames[0]];
    initialData = XLSX.utils.sheet_to_json(worksheet);
    console.log('initialData ')
    

    now you have the first worksheet of your copied file as JSON and can perform whatever changes you like.

    After using eg trim on every object you can write that JSON back to an Excel File

    let workbook1 = XLSX.utils.book_new();
    let worksheet1 = XLSX.utils.json_to_sheet();
    XLSX.utils.book_append_sheet(workbook1, worksheet1, 'WorksheetName');
    XLSX.writeFile(workbook1, 'newFile.xlsx');
    

    The first step is optional as you are only working inside the JSON copy an writing a new file afterwards, but I mentioned it as it was in the original question.