XLSXをデータ行に変換
ReoGrid JSON ドキュメントはロスレスですが冗長です。データそのもの — ヘッダー行をキーにした行オブジェクトの配列 — だけが欲しいときは、読み込み後にグリッドから表示値を読み取ります。
これは API への POST、DB への挿入、LLM への投入にちょうど良い形です。
ヘルパー
import type { ReogridInstance } from '@reogrid/pro';
/** 行0をヘッダーとして、ワークシートを行オブジェクトの配列で読み取る。 */
function sheetToRows(grid: ReogridInstance): Record<string, string>[] {
const ws = grid.worksheet;
// 1. スパースなセルスナップショットから使用範囲を求める。
const snapshot = ws.getExportSnapshot();
let lastRow = 0;
let lastCol = 0;
for (const cell of snapshot.cells) {
if (cell.row > lastRow) lastRow = cell.row;
if (cell.column > lastCol) lastCol = cell.column;
}
// 2. ヘッダー行 → 列キー(getDisplayText は*描画後*の値を返す)。
const headers: string[] = [];
for (let c = 0; c <= lastCol; c++) {
headers[c] = (ws.getDisplayText(0, c) || `col${c}`).trim();
}
// 3. 各データ行 → ヘッダーをキーにしたオブジェクト。
const rows: Record<string, string>[] = [];
for (let r = 1; r <= lastRow; r++) {
const row: Record<string, string> = {};
for (let c = 0; c <= lastCol; c++) {
row[headers[c]] = ws.getDisplayText(r, c) ?? '';
}
rows.push(row);
}
return rows;
}
使い方
import { createReogrid } from '@reogrid/pro';
const grid = createReogrid('#grid', { licenseKey: 'YOUR-LICENSE-KEY' });
await grid.loadFromFile(file);
const rows = sheetToRows(grid);
console.log(rows);
// [
// { Product: 'Widget', Price: '9.99', Qty: '40' },
// { Product: 'Gadget', Price: '24.50', Qty: '12' },
// ]
await fetch('/api/import', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(rows),
});
なぜ cell.value ではなく getDisplayText?
ws.getDisplayText(r, c)は描画後の値を返します。数式は評価され、数値書式が適用されます("1,200","$9.99")。人が見る値であり、たいていアプリが欲しい値です。grid.worksheet.cell(r, c).valueは生の入力を返します。数式セルではソース文字列("=B2*1.1")であり、計算結果ではありません。
文字列ではなく数値で取得
getDisplayText は文字列を返します。実数が必要な列は変換します。
const typed = rows.map((r) => ({
product: r.Product,
price: Number(r.Price.replace(/[^0-9.-]/g, '')), // $ や , を除去
qty: Number(r.Qty),
}));
メモ
- ヘッダーは行0を前提にしています。タイトル行がある場合は、実際のヘッダー行からループを始めてください。
- 末尾の空行・空列は、使用範囲を実セルのスナップショットから求めるため自動的に除外されます。
- 素の行ではなく、フル忠実度のドキュメント(スタイル・数式・結合)が欲しい場合は XLSXをJSONに変換を使ってください。
関連
- ExcelデータをアプリのJSONとして取り出す(記事)
- AIでスプレッドシートを一括処理(記事)
- JSONから一括読み込み — 逆方向