🚀 新規事業
csv-import
最終更新 2026年05月09日 / 40_新規事業/SCALE_Build/カタログ/機能集/csv-import.md
CSV インポートパーサー
用途
CSVファイルを配列にパース。クォート・カンマ・改行のエスケープ対応。
特徴
- ファイル選択
- クォートエスケープ
- ヘッダ行抽出
- 型変換オプション
コード(コピペ用)
export function parseCSV(text: string): Record<string, string>[] {
const lines: string[][] = [];
let row: string[] = []; let cell = ''; let inQuote = false;
for (let i = 0; i < text.length; i++) {
const c = text[i], next = text[i + 1];
if (inQuote) {
if (c === '"' && next === '"') { cell += '"'; i++; }
else if (c === '"') { inQuote = false; }
else { cell += c; }
} else {
if (c === '"') inQuote = true;
else if (c === ',') { row.push(cell); cell = ''; }
else if (c === '\n' || c === '\r') {
if (cell || row.length) { row.push(cell); lines.push(row); row = []; cell = ''; }
if (c === '\r' && next === '\n') i++;
}
else { cell += c; }
}
}
if (cell || row.length) { row.push(cell); lines.push(row); }
if (lines.length === 0) return [];
const headers = lines[0];
return lines.slice(1).map(r => Object.fromEntries(headers.map((h, i) => [h, r[i] ?? ''])));
}
// File input から読込:
// async function onFile(e) {
// const file = e.target.files[0];
// const text = await file.text();
// const rows = parseCSV(text);
// }
使い方
対象プロジェクトに該当ファイルをコピーして、props を流し込むだけ。
注意事項
- 依存パッケージを忘れず追加