LoginSignup
1
0

javascriptでCSVのinport,Export

Last updated at Posted at 2023-11-26

chartGPTを使用して試したことのメモ書き

1.jsを使用してCSVをimportし、Tableを作成
2.Tableの値を編集
3.Table上のデータをCSVとして出力

<!DOCTYPE html>
<html lang="ja">

<head>
    <meta charset="utf-8" />
    <title>Editable Table with CSV Export</title>
</head>

<body>
    <input type="file" id="csvInput" accept=".csv" onchange="handleFileSelect()" />
    <table id="editableTable">
        <!-- ヘッダー行はここに追加されます -->
    </table>

    <button onclick="exportTableToCSV()">Export to CSV</button>
    <button onclick="addRow()">Add Row</button>

    <script>
        function handleFileSelect() {
            const fileInput = document.getElementById('csvInput');
            const table = document.getElementById('editableTable');

            const file = fileInput.files[0];

            if (file) {
                const reader = new FileReader();

                reader.onload = function (e) {
                    const csvData = e.target.result;
                    displayCSVData(csvData, table);
                };

                reader.readAsText(file);
            }
        }

        function displayCSVData(csvData, table) {
            // CSVデータをパース
            const rows = csvData.split('\n');

            // ヘッダー行を処理
            const headerRow = table.createTHead().insertRow(0);
            const headers = rows[0].split(',');
            headers.forEach(header => {
                const th = document.createElement('th');
                th.textContent = header;
                headerRow.appendChild(th);
            });

            // データ行を処理
            for (let i = 1; i < rows.length; i++) {
                const rowData = rows[i].split(',');
                const newRow = table.insertRow(i);

                rowData.forEach(data => {
                    const cell = newRow.insertCell();
                    const editableContent = document.createElement('div');
                    editableContent.contentEditable = true;
					editableContent.classList.add('valueId');
                    editableContent.textContent = data;
                    cell.appendChild(editableContent);
                });
            }
        }

        function convertToCSV(data, header) {
            const rows = [];
            const header_length = header.length
            // データを3列に整理
            for (let i = 0; i < data.length; i += header_length) {
                const row = Array.from(data.slice(i, i + header_length));
                rows.push(row.join(','));
            }

            // CSVデータを文字列に変換
            //return rows.join('\n');
            return rows;
        }

        function exportTableToCSV() {
            const table = document.getElementById("editableTable");
            const elements = document.querySelectorAll('.valueId');
            const values = Array.from(elements).map(element => element.innerText);
            console.log(values);
            // CSVデータを格納する変数
            let csvData = [];

            // ヘッダー行
            const header = Array.from(table.querySelectorAll("thead th")).map(th => th.innerText);
            csvData.push(header.join(','));
            console.log(header)
            console.log(csvData)
            const rowdatas = convertToCSV(values,header);
            // データ行

            for (let i = 0; i < rowdatas.length; i++) {
                const rowData = Array.from(rowdatas[i].split(","))
                csvData.push(rowData.join(','));
            }

            // CSVデータを文字列に変換
            const csvString = csvData.join('\n');
            // CSVデータをファイルとしてダウンロード
            const blob = new Blob([csvString], { type: 'text/csv;charset=utf-8;' });
            const link = document.createElement("a");

            if (link.download !== undefined) {
                const url = URL.createObjectURL(blob);
                link.setAttribute("href", url);
                link.setAttribute("download", "table_export.csv");
                link.style.visibility = 'hidden';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            }
        }

        function addRow() {
            const table = document.getElementById("editableTable");
            const newRow = table.insertRow(table.rows.length);

            // 各セルにinputを追加
            for (let i = 0; i < table.rows[0].cells.length; i++) {
                const cell = newRow.insertCell(i);
                const editableContent = document.createElement("div");
                editableContent.contentEditable = true;
				editableContent.classList.add('valueId')
                cell.appendChild(editableContent);
            }
        }
    </script>
</body>

</html>

他の関数との組み合わせ???

let initialCsvData = null;

function loadCsvData(csvFilePath) {
  if (initialCsvData !== null) {
    // If data is already loaded, return a resolved Promise with the existing data
    return Promise.resolve(initialCsvData);
  }

  // Otherwise, load the CSV data
  return fetch(csvFilePath)
    .then(response => response.text())
    .then(data => {
      initialCsvData = data;
      return data;
    })
    .catch(error => {
      console.error('Error loading CSV file:', error);
      throw error;
    });
}

function updateFunction() {
  // Example: Load the first CSV data or reuse existing data
  loadCsvData('first_csv_file.csv')
    .then(data => {
      initializeChart(data);
      // You can call createTable or other functions using the same data
      createTable(data);
    })
    .catch(error => {
1
0
1

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