Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read EXCEL (.xlsx) file in TypeScript

I explored a lot to get the code to read the .xlsx file in the TypeScript environment but I couldn't get the solution, later I implemented the solution and added a question and answer here.

I have a file called "demo.xlsx" with UserIds and Code as you can see in the below image:

enter image description here

I need to create a function to get the list of UserIds and Code as:

[
    {
        "UserId": "B431A1A02A8211ED81",
        "Code": "SHUBH8099"
    },
    {
        "UserId": "9CD4C2E0287411",
        "Code": "SHUBH8100"
    },
    {
        "UserId": "8FBAFEE027C91",
        "Code": "SHUBH8101"
    },
    {
        "UserId": "5080ACD02B3311",
        "Code": "SHUBH8102"
    },
    {
        "UserId": "40FCD8602A6111",
        "Code": "SHUBH8103"
    },
    {
        "UserId": "E1F277B02B5211E",
        "Code": "SHUBH8104"
    }
]
like image 542
Shubham Verma Avatar asked Dec 17 '25 12:12

Shubham Verma


1 Answers

Here I implemented this problem in TypeScript:

I use "xlsx" npm module and required it.

Install: npm i xlsx --save

Use this npm module to read the file:

const xlsx = require('xlsx');

export const readExcelFile = async (filePath) => {
    try {
        const path = 'src/common/utils';
        const file = xlsx.readFile(`${path}/${filePath}`);
        let data = []
        const sheets = file.SheetNames
        for (let i = 0; i < sheets.length; i++) {
            const temp = xlsx.utils.sheet_to_json(
                file.Sheets[file.SheetNames[i]])
            temp.forEach((res) => {
                data.push(res)
            })
        }
        console.log(data);
        return data;
    }
    catch (err) {
        console.log(err);
    }
}

How to use this function:

import { readExcelFile } from 'src/common/utils/upload';

const uploadedFile = await readExcelFile('demo.xlsx');
console.log('uploadedFile :', uploadedFile);
return uploadedFile;

Result:

[
    {
        "UserId": "B431A1A02A8211ED81",
        "Code": "SHUBH8099"
    },
    {
        "UserId": "9CD4C2E0287411",
        "Code": "SHUBH8100"
    },
    {
        "UserId": "8FBAFEE027C91",
        "Code": "SHUBH8101"
    },
    {
        "UserId": "5080ACD02B3311",
        "Code": "SHUBH8102"
    },
    {
        "UserId": "40FCD8602A6111",
        "Code": "SHUBH8103"
    },
    {
        "UserId": "E1F277B02B5211E",
        "Code": "SHUBH8104"
    }
]
like image 161
Shubham Verma Avatar answered Dec 19 '25 07:12

Shubham Verma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!