TL;DR
xlsx-populate は Node.js とブラウザの両方で使用できる Excel 操作用ライブラリです。
インストールから作成・読み込み・書き込み・スタイル・保存までの手順をまとめています。
🧩 概要
xlsx-populate は、JavaScript で Excel ファイル(.xlsx)を 作成・変更・読み込み するための軽量ライブラリです。
帳票出力、レポート生成、テンプレートの差し替えなどに便利です。
📍Node.js(サーバー)とブラウザ(フロントエンド)の両方で動作します。
⚙️ インストール
xlsx-populate を npm または yarn を使用してインストールします:
npm install xlsx-populate
または
yarn add xlsx-populate
🚀 基本的な使い方
1️⃣ ライブラリのインポート
まず、JavaScript または TypeScript ファイルに xlsx-populate ライブラリをインポートします:
import XlsxPopulate from 'xlsx-populate';
2️⃣ 新しいワークブックの作成
新しいワークブックを作成するには、fromBlankAsync メソッドを使用します:
XlsxPopulate.fromBlankAsync()
.then(workbook => {
// ワークブックオブジェクトを使用して Excel ファイルを操作します
});
3️⃣ 既存ファイルの読み込み
既存のワークブックをファイルまたは URL から読み込むには、fromFileAsync または fromDataAsync メソッドを使用します:
// ファイルから読み込む
XlsxPopulate.fromFileAsync('./path/to/file.xlsx')
.then(workbook => {
// ワークブックオブジェクトを使用して Excel ファイルを操作します
});
// URL または ArrayBuffer から読み込む
fetch('https://example.com/file.xlsx')
.then(response => response.arrayBuffer())
.then(data => XlsxPopulate.fromDataAsync(data))
.then(workbook => {
// ワークブックオブジェクトを使用して Excel ファイルを操作します
});
🧾 シートの追加
新しいシートをワークブックに追加するには:
const sheet = workbook.addSheet('Report');
✍️ セルの書き込み・読み取り
セルにデータを書き込むには:
sheet.cell('A1').value('商品名');
sheet.cell('B1').value(1200);
const val = sheet.cell('B1').value(); // 1200
🎨 スタイルを適用
セルにスタイルを適用するには:
sheet.cell('A1').style({
bold: true,
italic: true,
fill: { type: 'solid', color: 'FFFF00' },
border: {
top: { style: 'thin', color: '000000' },
bottom: { style: 'thin', color: '000000' },
left: { style: 'thin', color: '000000' },
right: { style: 'thin', color: '000000' }
}
});
🔢 範囲の一括設定
セルの範囲を操作するには:
const range = sheet.range('A1:C3');
range.value([
['商品', '数量', '金額'],
['りんご', 10, 1200],
['みかん', 5, 600],
]);
🔗 セルの結合
セルを結合するには:
sheet.range('A1:C1').merged(true);
💾 保存
workbook.toFileAsync('./path/to/save.xlsx')
.then(() => {
console.log('ワークブックが正常に保存されました。');
});
ブラウザ(ダウンロード)
workbook.outputAsync()
.then(data => {
const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'workbook.xlsx';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
});
💼 実践例:売上レポートを自動生成
import XlsxPopulate from 'xlsx-populate';
async function buildSalesReport() {
const wb = await XlsxPopulate.fromBlankAsync();
const s = wb.sheet(0).name('Sales');
s.range('A1:C1').value([['商品名','数量','売上']]).style({ bold: true });
s.range('A2:C4').value([
['りんご', 10, 1200],
['みかん', 5, 600],
['ぶどう', 3, 1500],
]);
s.cell('B5').value('合計').style({ bold: true });
s.cell('C5').formula('SUM(C2:C4)');
await wb.toFileAsync('./sales-report.xlsx');
}
buildSalesReport();
💡 Tips
async/await で非同期処理をスッキリ記述
.formula() で数式をセット可能(計算は Excel 側で実行)
大量データには .range().value() が高速
Excel 側で表示形式を整えると見た目が綺麗になります
API リファレンス
完全な API リファレンスについては、公式の xlsx-populate ドキュメント を参照してください。