LoginSignup
1
0

Nuxt 3 + npm exceljs でブラウザからエクセルファイルをダウンロードさせる #3540

Posted at

ExcelJS

install

npm install exceljs

Vueファイルの例

<script setup>
import * as Excel from 'exceljs'

async function exportFile() {
  const workbook = new Excel.Workbook()

  // Sheet
  const worksheet = workbook.addWorksheet('My Sheet')

  // Header
  worksheet.columns = [
    { header: 'Id', key: 'id' },
    { header: 'Name', key: 'name' },
  ]

  // Rows
  worksheet.addRow([1, 'Alice'])
  worksheet.addRow([2, 'Bob'])

  // workbook to Blob
  const uint8Array = await workbook.xlsx.writeBuffer()
  const blob = new Blob([uint8Array], { type: 'application/octet-binary' })

  // Download
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  document.body.appendChild(a)
  a.download = `example.xlsx`
  a.href = url
  a.click()
  a.remove()
  URL.revokeObjectURL(url)
}
</script>

<template>
  <button @click="exportFile">Export XLSX</button>
</template>

概要

  • Exceljs でワークブックを組み立てる
  • Nuxtでダウンロードさせるには、Exceljsで作成したワークブックをBlobに変換した上で、ブラウザに対してはダウンロード処理を「偽装」する必要がありそうだ

ダウンロード例

image

参考

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

プロフィール・経歴

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0