Search code examples
excelangularfile-uploadimportxlsx

Angular get headers from excel uploaded using XLSX


I want to get the first row(name,email,mobile) as array from an uploaded excel file.

I am using XLSX.

I am getting whole data into array. But, I want only to read top line. because,

my excel file is quite large.

enter image description here

onFileChange(event) { //when user uploads xls file
    const fileList: FileList = event.target.files;
    if (fileList.length > 0) {
      const file: File = fileList[0];
      const reader = new FileReader();
      reader.onload = function (e) {
        const arrayBuffer = this.result,
          data = new Uint8Array(arrayBuffer),
          arr = new Array();
        for (let i = 0; i !== data.length; ++i) {
          arr[i] = String.fromCharCode(data[i]);
        }    
        const bstr = arr.join('');

        const workbook: XLSX.WorkBook = XLSX.read(bstr, { type: 'binary' });
        const firstSheetName: string = workbook.SheetNames[0];
        const worksheet: XLSX.WorkSheet = workbook.Sheets[firstSheetName];
        // getting all rows
        console.log(XLSX.utils.sheet_to_json(worksheet, { header: 1 })); 
        // I want to get top row only.
        console.log(XLSX.utils.decode_row('A1')); 

      };
      reader.readAsArrayBuffer(file);
    }
  }

Solution

  • I am using this code for single row header in excel sheet, but I want a two row header. Suggestions are welcome.

    var Heading =[
      [ "EMPLOYEE","SCORES","COMMENTS"]  
    ];
      
    const myworksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(this.emp ,{skipHeader:true});
    XLSX.utils.sheet_add_json(myworksheet,this.emp,{skipHeader:true , origin: 'A2'});
    XLSX.utils.sheet_add_aoa(myworksheet, Heading);