我想在创建excel文件后发送电子邮件。
我使用了nestjs和typeform,我的代码如下:
import * as XLSX from 'xlsx';
let file: Map<string, any> = new Map();
for (const t in UserType) {
const data = await this.myDataRepository.find({
select: ['userId', 'userName'],
where: {userType : t},
order: {
userId: 'DESC',
},
});
//createExcelFile
var wb = XLSX.utils.book_new();
var ws = XLSX.utils.json_to_sheet<UserGameCount>(data);
XLSX.utils.book_append_sheet(wb, ws, 'TestWB.xlsx');
var wbout = XLSX.write(wb, {
type: 'base64',
bookType: 'xlsx',
bookSST: false,
});
file.set(t, wbout);
}
const result = await this.commonService.testsendMail(
'myEmail@gmail',
file,
);
async testsendMail(email: string, file: Map<string, any>) {
try {
const att: {
filename: string;
contents: any;
contentTransferEncoding: string;
contentType: string;
}[] = [];
file.forEach((value: any, key: string) => {
att.push({
filename: key + '.xlsx',
contents: Buffer.from(value).toString('base64'),
contentTransferEncoding: 'base64',
contentType:
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
});
});
const mailOptions = {
from: 'your mail',
to: email,
subject: 'subject',
html: 'content',
attachments: att,
};
await transporter.sendMail(mailOptions);
} catch (error) {
console.log(error);
}
}
邮件发送正常。附件也会根据usertype的数量正常发送。
但文件大小为0kb
,无法打开。
即使我将数据更改为json格式,即使我更改XLSX。将选项写入缓冲区而不是base64,则会发生相同的错误。我怎么解决这个问题?
我解决了用excel4node
代替xlsx
生成excel的部分。
var wb = new XLSX.Workbook();
var ws = wb.addWorksheet(t);
for (let i = 0; i < data.length; i++) {
ws.cell(i + 1, 1).number(data[i].userId);
ws.cell(i + 1, 2).string(data[i].name);
}
const filename: string = new Date().getMonth() + '.xlsx';
const f = await wb.writeToBuffer();