Vueアプリケーションで、サーバーから提供されるExcelファイルのURLを利用してブラウザ上でプレビュー表示する要件に対応しました。初期実装ではxlsxライブラリを使用してデータを抽出・テーブル形式で表示していましたが、セルの整形やスタイルが失われ、見栄えが悪くなる問題がありました。
そこで、より高品質なプレビュー体験を実現するために、@vue-office/excelコンポーネントを導入しました。このライブラリは、単にファイルのURLを渡すだけで、Excelの見た目をほぼ忠実に再現したプレビューを提供します。
導入手順
# Excelプレビューコンポーネントのインストール
npm install @vue-office/excel vue-demi@0.14.6
# Vue 2.6以下の場合、追加で必要
npm install @vue/composition-api
実装例
<template>
<div class="preview-container">
<el-button @click="openPreview">プレビューを開く</el-button>
<el-dialog
title="Excelプレビュー"
:visible.sync="showPreview"
width="85%"
append-to-body
>
<vue-office-excel
v-if="showPreview"
:src="fileUrl"
style="height: 80vh; width: 100%"
@rendered="onRenderSuccess"
@error="onRenderError"
/>
</el-dialog>
</div>
</template>
<script>
import VueOfficeExcel from '@vue-office/excel';
import '@vue-office/excel/lib/index.css';
export default {
components: { VueOfficeExcel },
data() {
return {
fileUrl: '',
showPreview: false,
};
},
methods: {
async openPreview() {
try {
// サーバーからファイルURLを取得
const response = await this.$http.get('/api/excel-url');
this.fileUrl = response.data.url;
this.showPreview = true;
} catch (err) {
this.$message.error('ファイルの取得に失敗しました');
}
},
onRenderSuccess() {
console.log('プレビュー表示完了');
},
onRenderError(err) {
console.error('プレビュー表示エラー:', err);
this.$message.error('プレビューの表示に失敗しました');
}
}
};
</script>
<style scoped>
.preview-container {
padding: 20px;
}
</style>
この方法により、セルの結合、フォントスタイル、背景色など、Excel本来のレイアウトをほぼ完全に保持した状態でプレビュー表示が可能になります。ユーザー体験の向上と開発工数の削減を同時に実現できます。