node.js - 如何通过 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 文件中,并且在创建文件时,它已损坏
解决方案
对我有用的是这个,使用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();
推荐阅读
- ios - iOS 通用链接 - NSUserActivity 为零
- c# - 为 HttpClient 使用 GetStringAsync 与 GetString 有什么缺点吗?
- git - 当特定用户选择旧提交时,Git 推送新分支
- c - 程序收到信号 SIGABRT,已中止。如何消除此错误?
- cobol - 如何在 COBOL 中打印星形图案?
- angular - 如何在 rxjs 中的订阅中重构订阅
- python - Python BeautifulSoup - 在 Div Select 选项中获取值
- angular - 如何链接 RxJS 可观察的列表
- vue.js - 无法从我的路由器文件中解析组件 vue 文件
- java - Maven 没有将 reactjs 文件构建到我的 jar 文件中