JavaScript | 配列の全要素を連結して文字列を得る方法

JavaScript JavaScript
スポンサーリンク

では、CSV を読み込んでテーブル表示 → 編集 → 再ダウンロード までできる、初心者向けの HTML + JS サンプルを作ります。


<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>CSV 編集&ダウンロード</title>
<style>
  body { font-family: sans-serif; margin: 20px; }
  table { border-collapse: collapse; margin-top: 10px; }
  td, th { border: 1px solid #ccc; padding: 5px 10px; }
  td { min-width: 80px; }
  input[type="file"] { margin-bottom: 10px; }
  button { margin-top: 10px; }
</style>
</head>
<body>

<h2>CSV 編集&ダウンロードサンプル</h2>

<input type="file" id="csvFile" accept=".csv">
<button id="downloadBtn">CSV をダウンロード</button>

<div id="tableContainer"></div>

<script>
// CSV → 2次元配列
function csvToArray(csvStr, delimiter = ',') {
  return csvStr.split('\n').map(line => {
    return line.split(delimiter).map(item => item.replace(/^"(.*)"$/, '$1'));
  });
}

// 2次元配列 → CSV
function arrayToCSV(arr, delimiter = ',') {
  return arr.map(row => 
    row.map(item => {
      if (typeof item === 'string' && (item.includes(delimiter) || item.includes('\n'))) {
        return `"${item}"`;
      }
      return item;
    }).join(delimiter)
  ).join('\n');
}

// 配列 → HTML テーブル表示
function renderTable(data) {
  const container = document.getElementById('tableContainer');
  const table = document.createElement('table');
  table.innerHTML = '';
  data.forEach((row, i) => {
    const tr = document.createElement('tr');
    row.forEach((cell, j) => {
      const td = document.createElement(i===0?'th':'td');
      const input = document.createElement('input');
      input.value = cell;
      input.style.width = '100%';
      input.dataset.row = i;
      input.dataset.col = j;
      td.appendChild(input);
      tr.appendChild(td);
    });
    table.appendChild(tr);
  });
  container.innerHTML = '';
  container.appendChild(table);
}

// CSV ファイル読み込み
document.getElementById('csvFile').addEventListener('change', function(e){
  const file = e.target.files[0];
  if(!file) return;
  const reader = new FileReader();
  reader.onload = function(evt) {
    const text = evt.target.result;
    const data = csvToArray(text);
    renderTable(data);
  };
  reader.readAsText(file, 'UTF-8');
});

// CSV ダウンロード
document.getElementById('downloadBtn').addEventListener('click', function(){
  const table = document.querySelector('#tableContainer table');
  if(!table) return alert('CSV を読み込んでください');

  const data = Array.from(table.rows).map(tr => 
    Array.from(tr.cells).map(td => td.querySelector('input').value)
  );

  const csvStr = arrayToCSV(data);
  const blob = new Blob([csvStr], { type: 'text/csv' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = 'edited.csv';
  a.click();
  URL.revokeObjectURL(url);
});
</script>

</body>
</html>
HTML

このサンプルの使い方

  1. CSV ファイルを選択
    • ヘッダー行も含めて 2次元配列として読み込みます。
  2. テーブル上で編集可能
    • 入力欄に直接文字を変更できます。
  3. CSV を再ダウンロード
    • 「CSV をダウンロード」ボタンを押すと編集済み CSV が保存されます。

ポイント

  • csvToArray() で CSV → 配列
  • arrayToCSV() で配列 → CSV
  • <input> をテーブルに埋め込み編集可能に
  • Blob と URL.createObjectURL で簡単に CSV ダウンロード
タイトルとURLをコピーしました