首页 > 解决方案 > 如何通过 nodejs 在 S3 中创建 Excel 文件?

问题描述

我正在尝试创建一个脚本,该脚本将采用 JSON 对象并将其作为 xlsx 文件放入 S3 存储桶中

我计划将 SQL 查询集成到代码中,但现在将其限制为 JSON 以便于编码。我尝试使用 alasql 和 xlsx 来尝试创建 S3.putObject 主体,但输出会创建损坏的 excel 文件

var data = [{a:1,b:1,c:1},{a:1,b:2,c:1},{a:1,b:3,c:1}, {a:2,b:1,c:1}];
  var a = XLSX.utils.json_to_sheet(data);

  var params = {
  'Body' : Buffer.from(a),
  'Key': event.Key + '.xlsx',
  'Bucket': event.Bucket
};

s3.putObject(params).promise();

我希望数据将被放置在 S3 存储桶中的 xlsx 文件中,并且在创建文件时,它已损坏

标签: node.jsamazon-s3

解决方案


对我有用的是这个,使用sheetjs import xlsx from 'xlsx';


        // initiate the workbook
        const wb = xlsx.utils.book_new();

        // add properties to the sheet
        wb.Props = {
          Title: 'Books Borrowed',
          Subject: 'Borrowed Books',
          Author: 'Admin',
          CreatedDate: '2020-04-23',
        };

        // add a sheet
        wb.SheetNames.push('Borrowed');

        // I used aoa_to_sheet because I'm having an issue with json_to_sheet but was able to create a workaround, see: https://github.com/SheetJS/sheetjs/issues/1487#issuecomment-618767784
        // I find the aoa_to_sheet a much cleaner approach
        const ws = xlsx.utils.aoa_to_sheet(sheet);
        wb.Sheets.Borrowed = ws;

        // generate output as buffer
        const wbOut = xlsx.write(wb, {
          bookType: 'xlsx',
          type: 'buffer',
        });

        // upload to S3
        const data = await s3
          .putObject({
            Bucket: config.s3.s3BucketPublic,
            Key: 'filenameHere.xlsx',
            ACL: 'public-read',
            Body: wbOut,
            ContentType:
              'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
          })
          .promise();

推荐阅读