Search code examples
angularxlsxjszip

date is not correctly parsed while reading an excel file from a zip folder


I am uploading a zip folder from ui which has a excel file. I have written following code

getZipData(file: File) {
const jsZip = require('jszip');
let excelRecord: any[] = [];
let images: { path: string, image: string }[] = [];
let fileList: any[] = [];
const reader = new FileReader();
jsZip.loadAsync(file).then((zip: any) => {
  Object.keys(zip.files).forEach((filename) => {

    if (!zip.files[filename].dir && filename.includes('xlsx')) {
    
      zip.files[filename].async('ArrayBuffer').then((fileData: any) => { 

        const data = new Uint8Array(fileData);
        const arr = new Array();
        for (let i = 0; i != data.length; ++i) {
          arr[i] = String.fromCharCode(data[i]);
        }
        const bstr = arr.join("");
        const workbook = XLSX.read(fileData, { type: "binary" });
        const first_sheet_name = workbook.SheetNames[0];
        const worksheet = workbook.Sheets[first_sheet_name];
        excelRecord = XLSX.utils.sheet_to_json(worksheet);
        console.log(JSON.stringify(excelRecord));
        //{name:"abcd",birthdate:36141}  <---- this is the output
      });
    }
  })
})
}

In the output date (12-12-1998) is not parsed correctly It should be {name:"abcd",birthdate:"12-12-1998"} When i parse this date manually it creates 01/01/1970. How can i get exact date?


Solution

  • Change this line

     const workbook = XLSX.read(fileData, { type: "binary"});
    

    to

     const workbook = XLSX.read(fileData, { type: "binary", cellDates: true });
    

    you will get the date in Indian Standard Time then covert it as per your requirement

    example:

    var date = new Date(excelRecord.birthdate).toLocaleDateString();