0

I have an object like this:

obj = {'a': [1, 2, 3], 'b': [0, 0,0], 'c': [1, 0, 4]}

I display it in a html table like this:

Code | sum1 | sum2 | sum 3
a    | 1    |  2   | 3
b    | 0    |  0   | 0
c    | 1    |  0   | 4

And I want to export this table into excel. This is my code:

export() {
    let w = new Workbook();
    let ws = w.addWorksheet('Sheet 1');
    ws.addRow(['Code', 'sum1', 'sum2', 'sum3'])
    for (let i = 0; i < this.obj['a'].length; i++) {
      ws.addRow(['a', this.obj['a'][i]])
    }
    for (let i = 0; i < this.obj['a'].length; i++) {
      ws.addRow(['b', this.obj['b'][i]])
    }
    for (let i = 0; i < this.obj['a'].length; i++) {
      ws.addRow(['c', this.obj['c'][i]])
    }
}

but this won't add the objects on rows, but on columns(something like this:)

Code | sum1 | sum2 | sum3
a    | 1    |      |
a    | 2    |      | 
a    | 3    |      |
b    | 0    |      |
b    | 0    |      |
b    | 0    |      |
c    | 1    |      |
c    | 0    |      |
c    | 4    |      |

How can I solve this? Thank you for your time!

Tenzolinho
  • 922
  • 2
  • 15
  • 35
  • I would try just `ws.addRow(this.obj['a'])` without iterating the inner elements. – Andy G Mar 19 '19 at 10:24
  • This won't work, because the whole array `[1, 2, 3]` for example, will be added inside `a:sum1` cell – Tenzolinho Mar 19 '19 at 10:26
  • import { Workbook } from 'exceljs' – Tenzolinho Mar 19 '19 at 10:29
  • I am surprised it would add the whole array to sum1 but, also, how does it currently put a,b,c into the Code column? Anyway, because there are four columns but three values, I would first put the letter 'a' ('b' then 'c') into the array using unshift before attempting again with my suggestion above. – Andy G Mar 19 '19 at 10:33
  • Sorry, I've made some mistakes while writing the code above. Check the edit, please. – Tenzolinho Mar 19 '19 at 10:41
  • Sorry, but I don't really understand what you say. Can you be more explicit? – Tenzolinho Mar 19 '19 at 10:52

1 Answers1

1

You don't need to iterate all of the inner array elements, that is why it creates many rows.

Consider that addRow will add a single row each time, so you need to ensure that the array you will add has the same number of columns as the array ['Code', 'sum1', 'sum2', 'sum3']. Use unshift to insert the key ('a', 'b', 'c') at the front of each respective array.

this.obj['a'].unshift('a');
ws.addRow(this.obj['a']);

Do the same for 'b' and 'c'.

You could also unpack 'a' and its elements to a new array if you do not wish to modify the original.

(It would also be possible to iterate the obj keys rather than repeating the above lines three times.)


Iterating the keys to unshift could look like this:

let k;
for (k of Object.keys(this.obj)) {

    this.obj[k].unshift(k);
    ws.addRow(this.obj[k]);
}
Andy G
  • 19,232
  • 5
  • 47
  • 69