Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format date with SheetJS

Thank you in advance for taking a look at this question! I am trying to use SheetJS to read a .xlsx file but am having some trouble with a column of dates that is formatted via Excel as Custom "yyyy/mm/dd hh:mm:ss". All of these dates show up as large float values.

Here is the code to read the .xlsx file on upload:

uploadWorkbook(e) {
    let reader = new FileReader();
    reader.readAsBinaryString(e.target.files[0]);
    reader.onload = (e) => {
        let data = e.target.result;
        let workbook = XLSX.read(data, {type: 'binary'});
        let first_sheet_name = workbook.SheetNames[0];
        let worksheet = workbook.Sheets[first_sheet_name];
        let jsonObj = XLSX.utils.sheet_to_json(worksheet);
        console.log(jsonObj);
    }
}

As an example, the first object's date value is 43395.29775462963. I would even be okay with formatting all cells as strings if this is possible. Any help would be greatly appreciated!

Thanks everyone!

like image 271
sivs Avatar asked Nov 05 '18 23:11

sivs


2 Answers

So, I figured out that passing the raw option when converting the sheet to JSON outputs all cells as a string. So it would be:

let jsonObj = XLSX.utils.sheet_to_json(worksheet, {raw: false});
like image 153
sivs Avatar answered Sep 20 '22 05:09

sivs


This is my way:

 const target = e.target.result;
 const wb = XLSX.read(target,{type:'binary',cellText:false,cellDates:true});
 const wsname = wb.SheetNames[0];
 const ws = wb.Sheets[wsname];
 const data = XLSX.utils.sheet_to_json(ws, {header:1,raw:false,dateNF:'yyyy-mm-dd'});
like image 30
Charles G Avatar answered Sep 22 '22 05:09

Charles G