Search code examples
node.jsxlsxfs

Nodejs reading .xlsx file gives weird symbols


I'm trying to read *.xlsx file, convert it to json and write to another file. The thing is, when i'm trying to read *.xlsx file using fs.readFileSync method, i'm getting weird symbols as a result. Did anybody ever faced that? how to solve it?

enter image description here

Code is something like this:

const inputFilePath = path.join(__dirname, 'csv/123.xlsx')

const fileContent = fs.readFileSync(inputFilePath, 'utf-8')

console.log(fileContent)

running it with nodemon index.js


Solution

  • ReadFileSync will always return these characters because its not a text file that you are reading, if you want to convert Excel files to JSON, you need to use 3rd party library like xlsx.

    const xlsx= require('xlsx');
    
    const inputFilePath = path.join(__dirname, 'csv/123.xlsx');
    let File = xlsx.readFile(inputFilePath);
    let Content = xlsx.utils.sheet_to_json(File.Sheets[File.SheetNames[0]]);
    

    This will parse first sheet of your excel.