ac.js
const service = require("../service/model.service"); const urlencode = require("urlencode"); const helper = require("../../utils/helper"); module.exports = { /** * @description: 下载导入度量模板 * @param {type} * @return: */ "GET /model/metricsDown": async (ctx, bean) => { let excel = await service.metricsDown(bean); if (!excel) { throw new Error("下载失败"); } let name = urlencode(excel.sheetName + '.xlsx', "utf-8"); ctx.response.set( "Content-Disposition", "attachment; " + helper.setDownLoadFilename(ctx.req.headers["user-agent"], name) ); ctx.response.body = excel.buffer; // 返回在响应体里 }, /** * @description: 导入度量 * @param {type} * @return: */ "POST /model/metricsImport": async (ctx, bean) => { const file = ctx.request.files.file; // 获取上传文件 let result = await service.metricsImport(file, bean); return result }, }
serve.js
const dao = require("../dao/model.dao"); const mysql = require("mysql"); const h = require("../../utils/helper"); const { v4: uuidv4 } = require('uuid'); const xlsx = require("node-xlsx"); const path = require('path'); const fs = require('fs'); module.exports = { /** * @description: 下载导入度量模板 * @param {*} need * @return {*} */ async metricsDown() { var data = [['度量名称', '度量英文名', '度量SQL'], ['必填项', '必填项', '必填项']]; const sheetName = '导入度量模板'; var buffer = xlsx.build([{ name: sheetName + ".xlsx", data: data }]); return { sheetName, buffer, }; }, /** * @description: 导入度量 * @param {*} need * @return {*} */ async metricsImport(file, params) { // 创建可读流 if (!params.fileName || !params.code) throw new Error("参数不合法!!!"); const reader = fs.createReadStream(file.path); if (!params.fileName.endsWith('xls') && !params.fileName.endsWith('xlsx')) { throw new Error('请上传xls或xlsx格式的文件'); } let filePath = path.join(__dirname, "../../../download/") + `${file.name}`; // 创建可写流 const upStream = fs.createWriteStream(filePath); // 可读流通过管道写入可写流 reader.pipe(upStream); return filePath }, }
标签:xlsx,const,..,nodejs,koa,require,excel,return,度量 From: https://www.cnblogs.com/ht955/p/17450970.html