Home About
UXP , InDesign , Spreadsheet

UXP InDesign, エクセルデータを読んでInDesignテーブルにレンダリング

pokemon xlsx

エクセルデータ起点のなになに・・・というケースに備えて、UXP InDesign Scripting の読み込みサンプルを書きました。

詳しくは Github の InDesign UXP Script Examples の read-xlsx を見てください。 ポイントとなる部分だけコードを書き残します。

ローカルにあるエクセルファイルを開く

const storage = require("uxp").storage;
const fs = storage.localFileSystem;
const file = await fs.getFileForOpening({ types: ['xlsx'] });
if( file!=null ){
    const data = await file.read({format: storage.formats.binary});
    const readOptions = { type: 'array' };
    const workbook = xlsx.read(data, readOptions);
    const sheetNames = workbook.SheetNames;
    const worksheet = workbook.Sheets[sheetNames[0]];

UXP InDesign Scripting では、ローカルファイルを直接スクリプトから開くことができないらしい。

いや、そうでもないらしい。あとでこの件についてエントリーをつくる予定。

そこで、

require("uxp").storage.localFileSystem.getFileForOpeing({ types: ['xlsx'] });

を使って開いています。 このようにユーザーが明示的に開くファイルを選択する場合は問題ない。

残りのポイントは SheetJS でファイルのデータを読み取る部分です。 const data = await file.read({format: storage.formats.binary}) のようにしてファイルを読むことで、byteArray としてデータが読み込まれます。 あとは、SheetJS 側でも byteArray として読むために、{ type: 'array' } を指定してデータを読みます。

    const readOptions = { type: 'array' };
    const workbook = xlsx.read(data, readOptions);

残りのコードは InDesign ドキュメントの生成とテーブルの生成です。 これは ExtendScript 時代と特に変わりはないので、説明は省略します。

実行すると、以下の InDesign ドキュメントができます。

read-xlsx

以上です。

Liked some of this entry? Buy me a coffee, please.