我正在尝试创建一个脚本,该脚本将采用 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();
Run Code Online (Sandbox Code Playgroud)
我希望数据将放置在 S3 存储桶中的 xlsx 文件中,并且在创建文件时,它已损坏
对我有用的是这个,使用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();
Run Code Online (Sandbox Code Playgroud)
以下是对我有用的。
const Excel = require('exceljs');
const aws = require('aws-sdk');
let workbook = new Excel.Workbook();
workbook.creator = 'System';
workbook.lastModifiedBy = 'System';
workbook.created = new Date();
workbook.modified = new Date();
workbook.lastPrinted = new Date();
let worksheet = workbook.addWorksheet('SOME Data');
worksheet.columns = [{
header: 'somekey',
key: 'DeviceID'
}, {
header: 'Type',
key: 'Type'
}];
hcpData.forEach(element => {
worksheet.addRow({
somekey: element.DEVICEID,
Type: element.TYPE
});
});
worksheet.getRow(1).eachCell(cell => {
cell.font = {
bold: true
};
});
//configuring the AWS environment
aws.config.update({
accessKeyId: 'putyourkye',
secretAccessKey: 'putyourkye',
});
const s3 = new aws.S3();
const stream = new Stream.PassThrough();
workbook.xlsx.write(stream).then(() => {
return s3
.upload({
Key: Date.now() + '_XYZNAME.xlsx',
Bucket: 'abc-reports',
Body: stream,
ACL: 'public-read',
})
.promise()
.then(data => {
// do some task after upload
});
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2891 次 |
最近记录: |