Vue.jsでCSVファイルを読み込み、ブラウザ上にテーブル形式で表示する機能は、データ管理や帳票ビューア、インポート機能などで頻繁に使われます。本記事では、ファイルアップロードからCSVパース、テーブル表示までの一連の流れを、Composition APIを使って実装する方法を解説します。
実装の全体像
以下のステップでCSV読み込み処理を構成します:
- <input type=”file”>でCSVファイルを選択
FileReader
を使って中身を読み取る- CSV形式の文字列をパースして配列化
- 配列をテーブルで表示
テンプレート構成
<template>
<div>
<input type="file" accept=".csv" @change="handleFileUpload" />
<table v-if="csvData.length" border="1" cellpadding="8">
<thead>
<tr>
<th v-for="(header, index) in csvData[0]" :key="'head-' + index">
{{ header }}
</th>
</tr>
</thead>
<tbody>
<tr v-for="(row, rowIndex) in csvData.slice(1)" :key="'row-' + rowIndex">
<td v-for="(cell, cellIndex) in row" :key="'cell-' + cellIndex">
{{ cell }}
</td>
</tr>
</tbody>
</table>
</div>
</template>
スクリプト処理(Composition API)
<script setup>
import { ref } from 'vue'
const csvData = ref([])
const handleFileUpload = (event) => {
const file = event.target.files[0]
if (!file) return
const reader = new FileReader()
reader.onload = (e) => {
const text = e.target.result
const rows = text.split('\n').map(row =>
row.trim().split(',').map(cell => cell.replace(/^"|"$/g, ''))
)
csvData.value = rows.filter(row => row.length > 1)
}
reader.readAsText(file)
}
</script>
注意点と拡張ポイント
- カンマ区切り以外(タブやセミコロン)への対応が必要な場合は正規表現やCSVライブラリ(PapaParseなど)を活用
- 文字コードがUTF-8以外(Shift-JISなど)の場合、
readAsText(file, 'encoding')
で指定 - ヘッダーの存在を切り替える機能や、データの型推論などを追加するとより実用的
まとめ
Vue.jsでは標準APIとわずかなロジックで、CSVファイルの読み込みからテーブル表示まで簡単に実装できます。軽量なデータインポートやローカルでの閲覧用ツールを作成する際に有効であり、より複雑な構造への対応やバリデーション処理を加えることで、業務システムへの応用も可能です。