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, input[type="text"] { margin: 5px 0; }
  button { margin-right: 5px; }
  #controls { margin-bottom: 10px; }
</style>
</head>
<body>

<h2>CSV 高機能エディタ</h2>

<div id="controls">
  <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="delRow">最後の行削除</button>
  <button id="delCol">最後の列削除</button>
  <button id="downloadBtn">CSV ダウンロード</button>
  <br>
  検索: <input type="text" id="searchText" placeholder="検索文字">
  置換: <input type="text" id="replaceText" placeholder="置換文字">
  <button id="replaceBtn">置換実行</button>
  <button id="duplicateCell">選択セル複製</button>
</div>

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

<script>
let selectedCell = null;

// 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);
      // セルクリックで選択
      td.addEventListener('click', () => {
        if(selectedCell) selectedCell.style.backgroundColor = '';
        selectedCell = td;
        td.style.backgroundColor = '#cff';
      });
      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);
    td.addEventListener('click', () => {
      if(selectedCell) selectedCell.style.backgroundColor = '';
      selectedCell = td;
      td.style.backgroundColor = '#cff';
    });
    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);
    td.addEventListener('click', () => {
      if(selectedCell) selectedCell.style.backgroundColor = '';
      selectedCell = td;
      td.style.backgroundColor = '#cff';
    });
    tr.appendChild(td);
  });
});

// 行削除
document.getElementById('delRow').addEventListener('click', function(){
  const table = document.querySelector('#tableContainer table');
  if(!table || table.rows.length===0) return;
  table.deleteRow(table.rows.length-1);
});

// 列削除
document.getElementById('delCol').addEventListener('click', function(){
  const table = document.querySelector('#tableContainer table');
  if(!table || table.rows[0].cells.length===0) return;
  Array.from(table.rows).forEach(tr => tr.deleteCell(tr.cells.length-1));
});

// 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);
});

// 置換機能
document.getElementById('replaceBtn').addEventListener('click', function(){
  const search = document.getElementById('searchText').value;
  const replace = document.getElementById('replaceText').value;
  if(!search) return;
  const table = document.querySelector('#tableContainer table');
  Array.from(table.rows).forEach(tr => {
    Array.from(tr.cells).forEach(td => {
      const input = td.querySelector('input');
      if(input.value.includes(search)){
        input.value = input.value.split(search).join(replace);
      }
    });
  });
});

// 選択セル複製
document.getElementById('duplicateCell').addEventListener('click', function(){
  if(!selectedCell) return alert('セルを選択してください');
  const table = document.querySelector('#tableContainer table');
  const row = selectedCell.querySelector('input').dataset.row;
  const col = selectedCell.querySelector('input').dataset.col;
  const value = selectedCell.querySelector('input').value;
  const newRow = table.insertRow(Number(row)+1);
  Array.from(table.rows[0].cells).forEach((_,j)=>{
    const td = newRow.insertCell(j);
    const input = document.createElement('input');
    input.value = (j==col)?value:'';
    input.style.width = '100%';
    td.appendChild(input);
    td.addEventListener('click', () => {
      if(selectedCell) selectedCell.style.backgroundColor = '';
      selectedCell = td;
      td.style.backgroundColor = '#cff';
    });
  });
});
</script>

</body>
</html>
HTML

この拡張版の機能まとめ

  1. CSV 読み込み・ダウンロード
  2. 列・行の追加・削除
  3. セル選択と複製
  4. 検索・置換機能
  5. 区切り文字の変更(カンマ/セミコロン/タブ)

ポイント

  • <input> を使うことでセル編集可能
  • 選択したセルの複製や置換も簡単にできる
  • join()toString() の考え方を活かして CSV 文字列に変換
  • 初心者でも拡張可能なシンプル構造
タイトルとURLをコピーしました