Search code examples
javascriptnode.jsreactjsxlsx

Add Multiple Sheets in a workbook using npm XLSX in ReactJS


I'm following This Tutorial to generate excel reports. Now the guy in tutorial did his best to explain each step and I successfully created excel report following his steps. Now my problem is, I want to generate multiple sheets in one workbook. you know like 'Sheet1' | 'Sheet2' .... Any help will be greatly appreciated. Thanks

enter image description here


Solution

  • Here is a small sample that creates 2 sheets.

    Just use book_append_sheet function

    var ws_data = [
      ["Column 1"],
      [1]
    ];
    var ws = XLSX.utils.aoa_to_sheet(ws_data);
    
    
    var ws_data2 = [
      ["Column 2"],
      [2]
    ];
    var ws2 = XLSX.utils.aoa_to_sheet(ws_data2);
    
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, "SheetJS1");
    XLSX.utils.book_append_sheet(wb, ws2, "SheetJS2");
    
    XLSX.writeFile(wb, "sheetjs.xlsx");