Tenzolinho
Tenzolinho

Reputation: 982

export html table to excel Angular 6

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!

Upvotes: 0

Views: 966

Answers (1)

Andy G
Andy G

Reputation: 19367

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]);
}

Upvotes: 1

Related Questions