0

The solution to this may be simple but I cannot seem to think of an easier solution at present. I am using Excel.js and want to add values from an array to a specific set of cells. In this example E6:E25

The problem I face is that I cannot seem to select specific cells, only all of them in a column.

var array = ["4","3","3","3","3","8","2","4","5","2","2","6","4","3","8","5","4","3","2","2"]

workbook.xlsx.readFile('myFile.xlsx')
  .then(function() {
    var worksheet = workbook.getWorksheet(1);
    var column = worksheet.getColumn(5) // Selecting specific column
    column.eachCell(function(cell, rownumber){
      // eachCell count is 122, ideally not wanting to iterate 122 times
      // when only needing 20
      switch (cell['_address']) {
        case 'E6':
          worksheet.getCell(cell['_address']).value = array[0];
          break;
        case 'E7':
          worksheet.getCell(cell['_address']).value = array[1];
          break;
        case 'E8':
          worksheet.getCell(cell['_address']).value = array[2];
          break;
          // and so on 20 times
        default:
      }

    });

    return workbook.xlsx.writeFile('newFile.xlsx');
})

This is awful I know; I am looking to refactor this and make it a lot cleaner and efficient.

5
  • If everything is normalized, e.g., E6-E8...En, then you just need to translate the 6-n to 0-n. Commented Feb 5, 2018 at 20:54
  • Thanks for the comment Dave, not 100% sure on what you mean though sorry Commented Feb 5, 2018 at 20:56
  • worksheet.getCell('E8').value doesn't work? Commented Feb 5, 2018 at 20:59
  • You have a collection of cells. If they're ordered from E6-En then you can translate the cell address (essentially an index) to array index by subtracting 6. Commented Feb 5, 2018 at 21:00
  • If it's not regular then it depends on what you actually need. Or you could use a map instead of an array with cellAddress => value, or you could rethink the problem. Commented Feb 5, 2018 at 21:04

1 Answer 1

1

Doesn't a simple for loop like this do the same?

var array = ["4","3","3","3","3","8","2","4","5","2","2","6","4","3","8","5","4","3","2","2"];

for (i=0; i<array.length; i++) {
    col = i+6;
    worksheet.getCell('E'+col).value = array[i];
}
Sign up to request clarification or add additional context in comments.

2 Comments

@Richlewis Glad you worked it out, but that's what I said.
@DaveNewton apologies, couldn't see it in my head until i saw the code, appreciate you helping out

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.