SCALE — Build Lab
開発パターン · JAVASCRIPT PATTERN

CSV インポートパーサー

CATEGORY開発パターン TYPEJavaScript Pattern EFFORT60〜120分 DIFFICULTY
PRIMARY CODE
ts
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);
// }
前提条件
Tailwind CSS v4TypeScript 5
USE CASES
  • 任意のダッシュボードに組み込み

CSV インポートパーサー

:LiTarget: 用途

CSVファイルを配列にパース。クォート・カンマ・改行のエスケープ対応。

:LiSparkle: 特徴

  • ファイル選択
  • クォートエスケープ
  • ヘッダ行抽出
  • 型変換オプション

:LiCode: コード(コピペ用)

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

:LiHandPointer: 使い方

対象プロジェクトに該当ファイルをコピーして、props を流し込むだけ。

:LiAlertCircle: 注意事項

  • 依存パッケージを忘れず追加