🧠
kirovの初めての記事:csv途中挿入
const fs = require('fs');
/**
* 指定されたCSVファイルに新しい行データを挿入し、
* 指定された列名に基づいて並べ替えた後、
* 行番号を再付番します。
* @param {string} csvFilePath - CSVファイルのパス
* @param {string} newRowStr - 行番号を含まない新しい行データ
* @param {string} sortFieldName - 並び替えの基準となる列名
* @throws {Error} エラーが発生した場合は例外をスローします
*/
function insertStudentRow(csvFilePath, newRowStr, sortFieldName) {
try {
const data = fs.readFileSync(csvFilePath, 'utf8');
const lines = data.trim().split('\n');
if (lines.length === 0) throw new Error('CSVファイルが空です');
const header = lines[0];
const fieldNames = header.split(',');
const sortFieldIndex = fieldNames.indexOf(sortFieldName);
if (sortFieldIndex === -1) {
throw new Error(`列名 "${sortFieldName}" が見つかりません`);
}
const rows = lines.slice(1);
const parsedRows = rows.map(line => {
const parts = line.split(',');
return {
lineWithoutNumber: parts.slice(1).join(','),
sortKey: parseInt(parts[sortFieldIndex])
};
});
const newParts = newRowStr.split(',');
const newSortKey = parseInt(newParts[sortFieldIndex - 1]);
const newParsedRow = {
lineWithoutNumber: newRowStr,
sortKey: newSortKey
};
const insertIndex = parsedRows.findIndex(row => newSortKey < row.sortKey);
if (insertIndex === -1) {
parsedRows.push(newParsedRow);
} else {
parsedRows.splice(insertIndex, 0, newParsedRow);
}
const outputLines = [header];
parsedRows.forEach((row, index) => {
outputLines.push(`${index + 1},${row.lineWithoutNumber}`);
});
fs.writeFileSync(csvFilePath, outputLines.join('\n'), 'utf8');
} catch (error) {
throw error;
}
}
Discussion