一.excel导出是在开发中经常操作的内容,对于excel的导出也是有各种成熟的api组件
这里是最近的项目有通过ts处理,这里的内容通过ts
①引入const XlsxPopulate = require("xlsx-populate"); const XLSXChart = require("xlsx-chart");
通过命令行操作, pnpm xlsx-populate xlsx-chart
②对于excel的说明更有利于对构建excel的理解
1.整个单独的excel即为一个工作簿(workBook)
2.一个工作簿里面可以有很多工作表(sheet)
3.每个工作表有工作表的名称sheetName
4.每个工作表有头(header),体(body)存储数据
5.每列开始从a开始到之后都有唯一的.这里不多可以使用A1:${ 97+ header.lenth-1}.length(head.length)
二.上面说完之后就应该有熟悉的认识
XlsxPopulate.fromFileAsync(pathInfo.filePath).then(async (workbook) => {
//导出路径格式const filePath = `./${pathInfo.folderName}/TicketsReport_${moment().unix()}.xlsx`;
//工作表名const newSheetName = "ReportData";const newSheet = workbook.addSheet(newSheetName);
//头部const header = ["Brand","Branch code","Branch name(TC)",];
//体 数据存储位置 这里范围从A1开始后面的为获取具体的ASCll码const range = workbook.sheet(newSheetName).range(`A1:${String.fromCharCode(97 + header.length - 1).toUpperCase()}header.length`);range.value([header,...reportData.map((data) => [data.brandName,data.branchCode,data.branchName,]),]);// 写文件输出await workbook.toFileAsync(filePath);
}).catch((error) => {Logger.error(`Something went wrong - ${error?.message ?? JSON.stringify(error)}`, 'excel')});
___________________________________________________________________________
第二部分:
一.对于要将结果变.csv格式的纯文本格式的这种内容就简单很多了,
这个部分只是文字,只是header和body部分需要写上,之后加上换行符"/n"就可以
const header = [
"id",
"token",]
let body= "";csvContent.forEach((ticket) => {let rowData = '';header.forEach((key)=>{let value='';value = ticket[key]??' ';rowData += value + ",";});rowData= rowData.slice(0, -1) + "\n";body+= rowData;});
const headerString = header.join(",") + "\n";
const data= headerString+body
这里将内容转换成需要的内容之后,拼接起来,之后通过fs将结果导出即可
await fs.promises.writeFile(filePath,data,'utf-8');