3
0

CSVを表示する簡易htmlツール

Posted at

0.はじめに

CSVを参照したいけどエクセルがないし、入れられない。あってもインストールが手間。などという時があったので、htmlで参照できるように作ってみました。

1.作り方

  • メモ帳で新規テキストを作成し、以下のコードを張り付けます。
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CSVReader</title>
    <style>
        table {
            width: 100%;
            border-collapse: collapse;
            margin: 20px 0;
        }
        th, td {
            padding: 10px;
            border: 1px solid #ddd;
            text-align: left;
        }
        th {
            background-color: #f4f4f4;
        }
    </style>
</head>
<body>

    <h1>CSVReader</h1>
    
    <!-- CSVファイルを選択用input -->
    <input type="file" id="csvFileInput" accept=".csv" />

    <!-- テーブルを表示要素 -->
    <table id="csvTable"></table>

    <script>
        document.getElementById('csvFileInput').addEventListener('change', function(event) {
            const file = event.target.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    const content = e.target.result;
                    displayCSV(content);
                };
                reader.readAsText(file);
            }
        });

        function displayCSV(content) {
            const rows = content.split('\n').map(row => row.split(','));
            let table = '<tr>';
            rows[0].forEach(header => {
                table += `<th>${header.trim()}</th>`;
            });
            table += '</tr>';
            
            for (let i = 1; i < rows.length; i++) {
                table += '<tr>';
                rows[i].forEach(cell => {
                    table += `<td>${cell.trim()}</td>`;
                });
                table += '</tr>';
            }

            document.getElementById('csvTable').innerHTML = table;
        }
    </script>

</body>
</html>

  • 張り付けたテキストデータをCsvReader.htmというファイル名に書き換えます。
  • ここではCsvReaderとしましたが、名称は任意のものでよいです。
  • 拡張子表示していないとテキストデータは新規 テキスト ドキュメントなどという名称になっています。拡張子表示にしたうえで、拡張子もtxtからhtmに変更してください。

2.使い方

  • CsvReader.htmを実行します。

  • ファイルを選択をクリックしてCSVファイルを選択します。

image.png

こんな感じで表示されます。
image.png

これを表示しているCSVは以下のものです。

Clm1,Clm2,Clm3,Clm4,Clm55
りんご,2024/08/24,2024/08/25,1000,1箱
ぶどう,2024/08/24,2024/08/26,
なし,2024/08/24,,800,2箱
,2024/08/24,2024/08/26,800,3箱

その他

このCSVReaderはよくあるカンマ区切りをデリミタにしていますが、他のデリミタを使用している場合は以下を書き換えて下さい。

const rows = content.split('\n').map(row => row.split(','));

例えば空白区切りにしたい場合は以下のように書き換えます

const rows = content.split('\n').map(row => row.split(' '));
3
0
2

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