LoginSignup
0
0

クライアントサイドのみでExcel出力

Posted at

記事概要

クライアントサイドの処理のみで、事前に準備したTemplateであるExcelファイルの中身を更新・DLを実現する。

利用ライブラリ

  • xlsx-populate
  • FileSaver.js

スクリプト

<html lang="ja">
<head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx-populate/1.21.0/xlsx-populate.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.0/FileSaver.min.js"></script>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div style="margin:100 auto;width:400px;">
        D4 => <input id="D4" type="text" value="test1"></input>
        <hr />
        D5 => <input id="D5" type="date" value="2023-05-29"></input>
        <hr />
        <button id="btn">
            EXCEL EXPORT
        </button>
    </div>
</body>
</html>

<script>
    // https://github.com/dtjohnson/xlsx-populate
    const exportExcel = (url, values) => {
        fetch(url)
            .then(response => response.arrayBuffer())
            .then(async buffer => {
                const workbook = await XlsxPopulate.fromDataAsync(buffer)
                values.map((v) => workbook.sheet(v.sheet).cell(v.cell).value(v.value))
                const wbout = await workbook.outputAsync()
                const blob = new Blob([wbout], { type: 'application/octet-stream' })
                const fileName = `test_${new Date().getTime()}.xlsx`
                saveAs(blob, fileName)
            })
    }

    document.querySelector('#btn').addEventListener('click', () => {
        const url = './test.xlsx'
        const values = [
            { sheet: 'Sheet1', cell: 'D4', value: document.querySelector('#D4').value },
            { sheet: 'Sheet1', cell: 'D5', value: document.querySelector('#D5').value }
        ]
        exportExcel(url, values)
    })
</script>

上記htmlを作成して、同じ階層に「test.xlsx」を作成しておく。  

0
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
0
0