由一个 导出 扩展出来的一系列知识点

December 17, 2023
测试
测试
测试
测试
5 分钟阅读

在使用node-xlsx 做导出的时遇到了几个问题 现记录一下 以备查阅

首先代码如下

// 导出所有联系人
router.get('/exportContactsExcel', async function (req, res) {
  let data = [
    {
      name: '第一个sheet',
      data: [['字段1', '字段2', '字段3'], ['1', 'Michael', '99'], ['2', 'Tom', '98']]
    },
    {
      name: '第二个sheet',
      data: [['A1', 'B1'], ['A2', 'B2']]
    }
  ]

  // 将格式化的数据写如excel文件
  let buffer = xlsx.build(data)
  res.setHeader('Content-Type', 'application/vnd.openxmlformats')  // 设置excel的文件拓展名 MIME 类型
  res.setHeader('Content-Disposition', 'attachment; filename=' + 'export.xlsx') // 下载的文件名为export.xlsx
  res.end(buffer) // 返回的是一个buffer
})

首先是接口返回的是一个buffer的文件

然后 Content-type 是application/vnd.openxmlformats 这值是excel的文件扩展名的MIME类型 关于office的文件还有很多content-type可以设置

复制一下给大家看看

.doc application/msword
.dot application/msword
.docx application/vnd.openxmlformats-officedocument.wordprocessingml.document
.dotx application/vnd.openxmlformats-officedocument.wordprocessingml.template
.docm application/vnd.ms-word.document.macroEnabled.12
.dotm application/vnd.ms-word.template.macroEnabled.12
.xls application/vnd.ms-excel
.xlt application/vnd.ms-excel
.xla application/vnd.ms-excel
.xlsx application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
.xltx application/vnd.openxmlformats-officedocument.spreadsheetml.template
.xlsm application/vnd.ms-excel.sheet.macroEnabled.12
.xltm application/vnd.ms-excel.template.macroEnabled.12
.xlam application/vnd.ms-excel.addin.macroEnabled.12
.xlsb application/vnd.ms-excel.sheet.binary.macroEnabled.12
.ppt application/vnd.ms-powerpoint
.pot application/vnd.ms-powerpoint
.pps application/vnd.ms-powerpoint
.ppa application/vnd.ms-powerpoint
.pptx application/vnd.openxmlformats-officedocument.presentationml.presentation
.potx application/vnd.openxmlformats-officedocument.presentationml.template
.ppsx application/vnd.openxmlformats-officedocument.presentationml.slideshow
.ppam application/vnd.ms-powerpoint.addin.macroEnabled.12
.pptm application/vnd.ms-powerpoint.presentation.macroEnabled.12
.potm application/vnd.ms-powerpoint.template.macroEnabled.12
.ppsm application/vnd.ms-powerpoint.slideshow.macroEnabled.12

只有设置正确的content-type 浏览器,或者http才会知道知道怎么处理这个buffer,

最后

res.setHeader('Content-Disposition', 'attachment; filename=' + 'export.xlsx') // 下载的文件名为export.xlsx

这行代码我也不甚理解,猜想大概和Http的原理有关吧,设置了这个 在浏览器直接访问接口就是下载一个excel 名为export.xlsx

还望路过的大佬指点迷津.

另外: 前端调用接口时 直接 这样

 window.open('/exportContactsExcel')

因为浏览器自动打开excel 所以直接就下载了

另外如果想直接在浏览器打开这个excel 就看这篇博客

继续阅读

更多来自我们博客的帖子

如何安装 BuddyPress
由 测试 December 17, 2023
经过差不多一年的开发,BuddyPress 这个基于 WordPress Mu 的 SNS 插件正式版终于发布了。BuddyPress...
阅读更多
Filter如何工作
由 测试 December 17, 2023
在 web.xml...
阅读更多
如何理解CGAffineTransform
由 测试 December 17, 2023
CGAffineTransform A structure for holding an affine transformation matrix. ...
阅读更多