'use strict'; const fs = require('fs'); const xlsx = require('better-xlsx'); const path = require('path') const moment = require('moment') //递归创建目录 同步方法 async function makeDir (dir) { if (!fs.existsSync(dir)) { makeDir(path.dirname(dir)) fs.mkdirSync(dir, function (err) { if (err) { throw err } }); } } async function simpleExcelDown ({ data = [], header = [], fileName = moment().format('YYYY-MM-DD HH:mm:ss'), exp } = {}) { const fileDirPath = path.join(__dirname, `../../downloadFiles`) makeDir(fileDirPath) const file = new xlsx.File(); const sheet_1 = file.addSheet('sheet_1'); // header const headerStyle = new xlsx.Style(); headerStyle.align.h = 'center'; headerStyle.align.v = 'center'; headerStyle.border.right = 'thin'; headerStyle.border.rightColor = '#000000'; headerStyle.border.bottom = 'thin'; headerStyle.border.bottomColor = '#000000'; const headerRow = sheet_1.addRow(); const indexCell = headerRow.addCell(); indexCell.value = '序号' indexCell.style = headerStyle for (let h of header) { const cell = headerRow.addCell(); cell.value = h.title; cell.style = headerStyle } // data const style = new xlsx.Style(); style.align.h = 'left'; style.align.v = 'center'; style.border.right = 'thin'; style.border.rightColor = '#000000'; style.border.bottom = 'thin'; style.border.bottomColor = '#000000'; for (let i = 0; i < data.length; i++) { const row = sheet_1.addRow(); const indexCell = row.addCell(); indexCell.value = i + 1 indexCell.style = headerStyle for (let h of header) { const cell = row.addCell(); cell.value = data[i][h.key]; if (exp == 'patrol' || exp == 'maintenance') { if (h.key == 'projectType') { let type = data[i][h.key] if (type == 'road') { cell.value = '道路' } else if (type == 'bridge') { cell.value = '桥梁' } else if (type == 'culvert') { cell.value = '涵洞' } else if (type == 'other') { cell.value = '其他' } continue } if (h.key == 'reportType') { let type = data[i][h.key] if (type == 'patrol') { cell.value = '巡查' } else if (type == 'conserve') { cell.value = '养护' } continue } } cell.style = style } } const savePath = path.join(fileDirPath, fileName) await new Promise(function (resolve, reject) { file.saveAs() .pipe(fs.createWriteStream(savePath)) .on('finish', () => { resolve() }); }) return savePath } module.exports = { simpleExcelDown }