Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

javascript json to excel

import * as ExcelJS from 'exceljs';

function bufferToFile(
    buffer,
    filename,
    type = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
  ) {
    let blob = new Blob([buffer], { type });
    const anchor = document.createElement('a');
    const url = URL.createObjectURL(blob);
    anchor.href = url;
    anchor.download = filename;
    document.body.appendChild(anchor);
    anchor.click();
    document.body.removeChild(anchor);
    URL.revokeObjectURL(url);
  }

async function exportToExcel($event) {
    const workbook = new ExcelJS.Workbook();
    const worksheet = workbook.addWorksheet('My Sheet');

    worksheet.columns = [
      { header: 'Id', key: 'id', width: 10 },
      { header: 'Name', key: 'name', width: 32 },
      { header: 'D.O.B.', key: 'DOB', width: 10, outlineLevel: 1 },
    ];
    worksheet.getColumn(2).alignment = {
      vertical: 'middle',
      horizontal: 'center',
      wrapText: true,
    };
    worksheet.addRow([3, 'Sam
Sung', new Date()]);
    worksheet.addRow({
      id: 1,
      name: 'John Doe',
      DOB: new Date(1994, 10, 10),
    });
    const filename = 'Export.xlsx';
    const buffer = await workbook.xlsx.writeBuffer();
    this.bufferToFile(buffer, filename);
  }
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #javascript #json #excel
ADD COMMENT
Topic
Name
5+4 =