要实现AWS无服务器Excel下载,可以使用以下步骤:
import boto3
from openpyxl import Workbook
def lambda_handler(event, context):
# 创建一个工作簿
wb = Workbook()
# 在工作簿中创建一个工作表
ws = wb.active
# 向工作表中添加数据
ws['A1'] = 'Hello'
ws['B1'] = 'World'
# 将工作簿保存到本地临时文件
tmp_file = '/tmp/my_excel.xlsx'
wb.save(tmp_file)
# 将临时文件上传到S3存储桶
s3 = boto3.client('s3')
s3.upload_file(tmp_file, 'my_bucket', 'my_excel.xlsx')
return {
'statusCode': 200,
'body': 'Excel file uploaded to S3'
}
接下来,创建一个API Gateway端点,将其与Lambda函数关联。这将允许您通过API调用Lambda函数。
在API Gateway中创建一个GET方法,并将其与Lambda函数关联。这将允许您从前端应用程序调用API,并触发Excel文件的生成和上传。
在前端应用程序中,您可以使用AWS SDK或使用HTTP GET请求调用API Gateway端点。以下是使用JavaScript的示例代码:
const downloadExcel = () => {
fetch('API_GATEWAY_ENDPOINT', { method: 'GET' })
.then(response => response.json())
.then(data => {
// 从S3存储桶下载Excel文件
window.location.href = `https://s3.amazonaws.com/my_bucket/my_excel.xlsx`;
})
.catch(error => console.log(error));
};
在上面的代码中,将API_GATEWAY_ENDPOINT
替换为您创建的API Gateway端点的URL。
这样,当您调用downloadExcel
函数时,它将触发API Gateway端点并从S3存储桶下载生成的Excel文件。