'writeBuffer of ExcelJS doesn't return Buffer type

I'm using exceljs with Typescript in my project. But writeBuffer() function returns ExcelJS.Buffer instead of Buffer type. And since ExcelJS.Buffer inherits from ArrayBuffer, converting ArrayBuffer to Buffer will break excel file. Does anyone have a solution to this problem? Thanks in advance!

declare interface Buffer extends ArrayBuffer { }
let resultExcel: Buffer; // buffer
const tmpResultExcel: ExcelJS.Buffer = await tmpWorkBook.xlsx.writeBuffer(); // arraybuffer
resultExcel = Buffer.from(tmpResultExcel); // doesn't work well


Solution 1:[1]

Actually, the problem with tmpWorkBook.xlsx.writeBuffer(); comes from a wrong returned type definition, in my point of view.

if you try Buffer.isBuffer(tmpResultExcel), you see that tmpResultExcel is an actual JavaScript Buffer.

You can solve the type issue with

const tmpResultExcel: any = await tmpWorkBook.xlsx.writeBuffer();

and you can use tmpResultExcel as a buffer in your code.

Solution 2:[2]

I came across this one too and this is 2022 with exceljs' latest version (4.3.0 at time of writing).

As @Frédéric Lang stated it is indeed a typing problem. Moreover even though inspecting the provided types did not lead to a clear solution, as the workbook.xlsx.writeBuffer() function's signature tells us it returns a plain Buffer.

Instead of converting the dodgy exceljs.Buffer instance to any, you may just want to "cast" it to a proper Buffer after an await.

private async writeXlsxBuffer(data: BillingSummaryFileLine[]): Promise<Buffer> {
        const workbook = new exceljs.Workbook();
        await workbook.xlsx.readFile("my_model.xlsx");
        ...
        return await workbook.xlsx.writeBuffer() as Buffer;
    }

You will have to make sure this is actually a Buffer though, as using the as keyword Typescript will assume you know what you are doing casting one object to another type.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Frédéric Lang
Solution 2 jpramondon