Search code examples
javascripthtmlexcelxlsxsheetjs

Start writing data to excel in some position SheetJS


I don't know how to properly pose my question but I have code that takes HTML table data and puts it to excel but it starts it at position A1 and let's say I want to start at C3.

And being here can I import some xlsx with styling make a copy of it and populate it with this method?

var t = document.getElementsByTagName("table")[0];

    var wb1 = XLSX.utils.table_to_sheet(t);
    var wb2 = XLSX.utils.table_to_sheet(t);

    var wb = XLSX.utils.book_new();

    XLSX.utils.book_append_sheet(wb, wb1, "Sheet 1");
    XLSX.utils.book_append_sheet(wb, wb2, "Sheet 2");

    var wbout = XLSX.write(wb, {
        bookType: 'xlsx',
        bookSST: true,
        type: 'binary'
    });


    saveAs(new Blob([s2ab(wbout)], {
        type: "application/octet-stream"
    }), 'data.xlsx');


    function s2ab(s) {
        var buf = new ArrayBuffer(s.length);
        var view = new Uint8Array(buf);
        for (var i = 0; i < s.length; i++) view[i] = s.charCodeAt(i) & 0xFF;

        return buf;
    }    

}
<table>
 <tr>
  <td>Emil</td>
  <td>Tobias</td>
  <td>Linus</td>
 </tr>
 <tr>
  <td>26</td>
  <td>24</td>
  <td>20</td>
  </tr>
</table>
<button type="button" onclick="downloadXlsx()">Excel download</button>


Solution

  • It's very easy.

    Change this...

    var wb1 = XLSX.utils.table_to_sheet(t);
    var wb2 = XLSX.utils.table_to_sheet(t);
    

    ...to this.

    var wb1 = XLSX.utils.table_to_sheet(t, {origin: 'C3'});
    var wb2 = XLSX.utils.table_to_sheet(t, {origin: 'C3'});