0

I'm having a problem parsing an ".xlsx" or ".xls" file with SheetJS ("xlsx" on npm) i don´t know what I'm doing wrong, but I always get the same output

[
{
    "__EMPTY": "i"
},
{
    "__EMPTY":"«Z.7¦§dÞZµìe°

I'm using an empty controller in loopback 4 in case you recognize the syntax, and the problem doesn't seem to bee a loopback since I'm able to save the file on the server and open it without a problem.

It seems that xlsx module it's unable to parse my files for some reason, can anyone take a look and see if something it's wrong?

Here it's my code:

import { inject } from '@loopback/context';
import { ParamsDictionary, RequestHandler } from 'express-serve-static-core';
import * as multer from "multer";
import { unlinkSync } from "fs";
import * as xlsx from "xlsx"
import {
  requestBody,
  RestBindings,
  RequestBodyObject,
  post,
  Request,
  Response
} from '@loopback/rest';

const MULTIPART_FORM_DATA: RequestBodyObject = {
  description: 'multipart/form-data value.',
  required: true,
  content: {
    'multipart/form-data': {
      // Skip body parsing
      'x-parser': 'stream',
      schema: { type: 'object' },
    },
  },
}

export class TemplateActionsController {
  constructor() { }

  @post('/parse-template', {
    responses: {
      200: {
        content: {
          'multipart/form-data': {
            schema: {
              type: 'object',
            },
          },
        },
        description: '',
      },
    },
  })
  async parseTemplate(
    @requestBody(MULTIPART_FORM_DATA)
    request: Request,
    @inject(RestBindings.Http.RESPONSE) response: Response,
  ): Promise<object> {
    //const storage = multer.memoryStorage();
    const storage = multer.diskStorage({
      filename: (req: Request<ParamsDictionary>, file: Express.Multer.File, callback: (error: Error | null, filename: string) => void) => {
        callback(null, file.originalname);
      }
    });
    const upload = multer.default({ storage });
    return new Promise<object>((resolve, reject) => {
      let middleware: RequestHandler<ParamsDictionary> = upload.any();
      console.log('----------------------------------------------------------');
      //console.log(request);
      middleware(request as any, response as any, (err: any) => {
        if (err) return reject(err);

        let arrFiles: Express.Multer.File[];
        arrFiles = (request as Express.Request).files as Express.Multer.File[];

        console.log('----------------------------------------------------------');
        console.log(arrFiles[0]);

        let workbook: xlsx.WorkBook = xlsx.read(arrFiles[0].path);
        var sheet_name_list: string[] = workbook.SheetNames;
        let firstSheet: xlsx.WorkSheet = workbook.Sheets[sheet_name_list[0]]

        let strResult: any = xlsx.utils.sheet_to_json(firstSheet);

        console.log('----------------------------------------------------------');
        console.log(sheet_name_list);
        console.log('----------------------------------------------------------');
        console.log(strResult);

        try {
          unlinkSync(arrFiles[0].path);
        } catch (e) {
          //error deleting the file
        }

        resolve(strResult);
      });
    });
  }
}

the line that parses the file it's this one:

let strResult: any = xlsx.utils.sheet_to_json(firstSheet);

My input excel file (template.xlsx) only has simple data in the first sheet:

6 rows and 3 columns with simple text data

I can't find any other issue that looks like this anywhere.

If anyone can help please tell me. Much appreciated. Omar

Mustafa
  • 977
  • 3
  • 12
  • 25

1 Answers1

0

It seems that I was using:

let workbook: xlsx.WorkBook = xlsx.read(arrFiles[0].path);

instead of:

let workbook: xlsx.WorkBook = xlsx.readFile(arrFiles[0].path);

It was my mistake, now everything it's working fine.