express中实现将mysql中的数据导出为excel

express中实现将mysql中的数据导出为excel

安装node-excel

javascript 复制代码
cnpm install node-xlsx -S

封装公用的导出方法

javascript 复制代码
/**
 * 查询
 * @param tableName: 表名
 * @param sqlJson:需要拼接的SQL
 * @returns {Promise<unknown>}
 */
const find = (tableName, sqlJson) => {
  return new Promise((resolve, reject) => {
    const sql = sqlJson ? `SELECT * FROM ${tableName} WHERE ${sqlJson}` : `SELECT * FROM ${tableName}`
    pool.query(sql, (error, results) => {
      if (error) {
        reject({
          status: false,
          msg: error
        })
        logger.error(JSON.stringify(error))
      } else {
        resolve({
          status: true,
          data: results
        })
      }
    })
  })
}
/**
 * 导出
 * @param tableName: 表名
 * @param tableHeader:excel表头信息
 * @param sqlJson:需要拼接的SQL语句
 * @returns {Promise<unknown>}
 */
const exportTableDataToExcel = (tableName, tableHeader, sqlJson) => {
  return new Promise((resolve, reject) => {
    find(tableName, sqlJson).then(({ status, msg, data }) => {
      if (status && data.length > 0) {
        // 定义excel表格的表头和内容
        const excelData = [
          tableHeader,
          ...data.map(item => Object.values(item))
        ]
        // 使用node-xlsx模块生成excel文件
        const buffer = xlsx.build([{ name: 'Sheet1', data: excelData }])
        resolve({
          status: true,
          data: buffer
        })
      } else {
        reject({
          status: false,
          msg: msg || '导出失败!'
        })
      }
    }).catch(err => {
      reject({
        status: false,
        msg: err || '导出失败!'
      })
    })
  })
}

node-xlsx需要的数据格式

javascript 复制代码
const excelData = [
	['日志主键', '模块标题',...],
	[1, 'test1',...],
	[2, 'test2',...]
]

编写导出excel接口

javascript 复制代码
exportFile(req, res) {
    const tableHeader = ['日志主键', '模块标题', '业务类型', '方法名称', '请求方式', '操作类别', '操作人员', '部门名称', '请求URL', '主机地址', '操作地点', '请求参数', '返回参数', '操作状态', '错误消息', '操作时间']
    exportTableDataToExcel('sys_oper_log', tableHeader, null).then(({ status, msg, data }) => {
      if (status && data) {
        // 设置返回的http header信息,告诉浏览器该文件是一个excel文件
        res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8')
        res.setHeader('Content-Disposition', 'attachment; filename=' + encodeURIComponent('导出数据.xlsx'))
        // 将生成的excel文件发送给客户端
        res.send(data)
      } else {
        res.sendError(msg || '导出操作日志失败!')
      }
    }).catch(err => {
      res.sendError(err || '导出操作日志失败!')
    })
  }

编写swagger注释

javascript 复制代码
/**
 * @swagger
 * /operlog/export:
 *   post:
 *     tags:
 *       - 操作日志-导出操作日志
 *     summary: 导出操作日志
 *     produces:
 *       - application/json
 *     responses:
 *       200:
 *         description: 成功
 *       400:
 *         description: 失败
 *     security:
 *       - Authorization:
 */
router.post('/export', exportFile)

apifox调用接口

swagger-ui调用接口

下载文件效果

参考链接

参考链接1
参考链接2

相关推荐
jaysee-sjc5 分钟前
【苍穹外卖】Day01:从零认识企业级项目开发
java·开发语言·数据库·mysql·spring·intellij-idea·mybatis
实心儿儿1 小时前
MySQL — 库的操作
数据库·mysql·oracle
bksczm1 小时前
MySQL基础篇之索引
数据库·sql·mysql
bksczm2 小时前
MySQL基础篇之事务
linux·数据库·sql·mysql
bksczm2 小时前
MySQL基础篇之视图与用户管理
linux·数据库·sql·mysql
香菜TTT2 小时前
怎么实现MySQL的主从同步机制
数据库·mysql
独泪了无痕16 小时前
SQL函数实战:GREATEST与LEAST的技巧
数据库·sql·mysql
麻辣布丁16 小时前
MySQL篇面试题模拟
mysql
这个DBA有点耶17 小时前
MySQL 8.0.20移除了Block Nested Loop,之前学的JOIN优化知识还适用吗?
数据库·mysql·架构
E-iceblue17 小时前
Excel 列转行/行列转换全指南:从 4 种常见解法到 Python 批量自动化
python·excel·python库·spire.xls