[[ExcelJS]]で特定シートのセル情報を **すべてstring型で** 取得する方法。 ## 確認環境 - [[ExcelJS]] v4.4.0 - [[Deno]] v2.1.4 ### Excelファイル 以下の[[スプレッドシート]]を変換したものを使う。 ![[Pasted image 20250102175314.png]] - `B6` セルは数式 (`B3 + 1`) が埋め込まれている ## 方法 `eachRow` と `eachCell` で `Excel.Cell` 型のセル情報を取得し、`toString()` で文字列としての情報を取得する。 ```ts import Excel from "exceljs"; const workbook = new Excel.Workbook(); await workbook.xlsx.readFile("./exceljs-test.xlsx"); const sheet = workbook.worksheets[0]; const rows: string[][] = []; sheet.eachRow((row) => { const cells: string[] = []; row.eachCell((cell) => { cells.push(cell.toString()); }); rows.push(cells); }); console.log(JSON.stringify(rows, null, 2)); ``` 結果は以下のようになる。 ```json [ [ "項目名", "値" ], [ "bool", "true" ], [ "number", "123" ], [ "string", "hoge" ], [ "date", "Wed Jan 01 2025 09:00:00 GMT+0900 (Japan Standard Time)" ], [ "formula", "124" ], [ "link", "https://minerva.mamansoft.net/" ], [ "color", "red" ] ] ``` > [!caution] > 日付だけは見た目と異なるフォーマットになるので注意。 ## 参考: getSheetValues() を使った場合 出力コード。 ```ts import Excel from "exceljs"; const workbook = new Excel.Workbook(); await workbook.xlsx.readFile("./exceljs-test.xlsx"); const sheet = workbook.worksheets[0]; const values = sheet.getSheetValues(); console.log(JSON.stringify(values, null, 2)); ``` 以下のように出力される。 - 値は型に準拠したものになる - 数式やリッチテキストの場合はprimitive以外の型になる ```json [ null, [ null, "項目名", "値" ], [ null, "bool", true ], [ null, "number", 123 ], [ null, "string", "hoge" ], [ null, "date", "2025-01-01T00:00:00.000Z" ], [ null, "formula", { "formula": "B3 + 1", "result": 124 } ], [ null, "link", { "text": "https://minerva.mamansoft.net/", "hyperlink": "https://minerva.mamansoft.net/" } ], [ null, "color", "red" ] ] ```