使用node-xlsx生成Excel后上传出现引号问题的解决咨询
问题
我用node-xlsx把简单数据结构写入新Excel文件,本地查看时单元格数据没有引号,但通过自动化上传到浏览器后,文件因为所有字符串值被加上引号而被拒绝——除了数字33228之外,其他值都受影响。我试过用正则replace()但没用,想知道怎么阻止这种行为,怀疑问题出在Playwright的fileChooser上传环节。
相关代码
Excel生成代码
export async function createExcelFile(testInfo, fileType, adaptationId) { const [tomorrow, nextMonth] = await getDatesForFiles(); const data = [ { 'storeNumber': 33228, 'adaptationId': parseInt(adaptationId), 'effectiveFrom': tomorrow.replaceAll('"', ''), 'effectiveTo': nextMonth.replaceAll('"', '') } ]; // @ts-ignore const buffer = xlsx.build([{name: "Sheet One", data: data}], { cellDates: false }); //write the buffer to a file in a temp folder const tempFileName = uuid.v4() + '.xlsx'; const tempFilePath = path.join(process.cwd(), 'src' ,'test-data', 'temp-files', tempFileName); fs.writeFileSync(tempFilePath, buffer); return [tempFileName, buffer]; }
Playwright上传代码
await fileChooser.setFiles({ name:fileName, mimeType:'application/vnd.ms-excel', buffer: Buffer.from(buffer) });
解决方案
1. 修正node-xlsx的数据处理逻辑
先确认tomorrow和nextMonth在替换后确实没有隐藏引号,可在生成buffer前打印data对象检查。如果数据本身没问题,尝试显式指定单元格类型,强制字符串值以纯文本形式写入,避免自动添加引号:
const data = [ { 'storeNumber': 33228, 'adaptationId': parseInt(adaptationId), 'effectiveFrom': { v: tomorrow.replaceAll('"', ''), t: 's' }, // t:'s'表示字符串类型 'effectiveTo': { v: nextMonth.replaceAll('"', ''), t: 's' } } ];
注:原代码里的"是HTML转义的双引号,直接替换"更准确。
2. 修复Playwright的上传配置
你当前用Buffer.from(buffer)重复转换已生成的Excel buffer,可能破坏文件结构;同时MIME类型也选错了——xlsx格式的正确MIME类型是application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,旧的vnd.ms-excel是针对xls格式的,会导致浏览器解析出错。修改后的代码:
await fileChooser.setFiles({ name: fileName, mimeType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', buffer: buffer // 直接使用node-xlsx生成的原始buffer });
3. 验证文件一致性
对比本地生成的temp文件和上传用的buffer:读取本地文件的buffer,和函数返回的buffer做字节对比,如果不一致,说明生成环节有问题;如果一致,重点排查浏览器端的文件解析逻辑。
内容的提问来源于stack exchange,提问作者Steerpike
相关产品推荐
相关产品推荐

