Return excel file from AWS Lambda function


I’m trying to return an excel file through Lambda. It succeeded, but the content is only the base64 encoded string of the file.

Here’s the code:

const xl = require("excel4node")

module.exports.handler = async () => {
    var wb = new xl.Workbook()
    var ws = wb.addWorksheet('Sheet 1')
    const cols = [ "col1", "col2" ]
    cols.forEach((c,i) => { ws.cell(1, i+1).string(c) })
    const buffer = await wb.writeToBuffer()
    return {
        statusCode: 200,
        headers: {
            'Access-Control-Allow-Origin': "*",
            'Access-Control-Allow-Methods': "*",
            'Content-type' : "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            'Content-Disposition': `attachment; filename="test.xlsx"`,
        isBase64Encoded: true,
        body: buffer.toString('base64')

and this is what’s generated

I’m using Serverless framework, and I’ve set contentHandling config to CONVERT_TO_BINARY.

Many thanks,


solved! after rereading @jarmod’s answer above, turns out I had not set the API binary media type to ‘*/*’

added apiGateWay.binaryMediaTypes in serverless config file and it worked

Answered By – Hariz

Answer Checked By – Clifford M. (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.