チャート(グラフ)の基本 — 追加・タイトル・型・系列/軸の読み戻し・削除
level: intermediate / verified: 2026-10-01 / 4言語タブ対応 / English
やりたいこと
ワークシートのデータ表からチャート(グラフ)を作成する。 縦棒グラフと折れ線グラフの 2 種類を作り、タイトル・凡例・軸を設定し、 作成した内容をプロパティとして読み戻して検証する。最後にチャートを削除する。
チャートは見た目をコンソールから確認できないため、このサンプルでは 型・タイトル文字列・系列の値・軸の設定値・チャート個数を console.log で出力し、 意図どおりに作れたかをプログラムで確かめられるようにしている。
対象クラス
チャートは「枠(ChartObject)」と「中身(Chart)」の 2 層に分かれる。
| クラス | 取得方法 | 役割 | |
|---|---|---|---|
chart.ChartObject | ws.addChartObject(name, left, top, w, h) / `ws.getChartObject(name\ | index)` | シート上の配置枠。位置・サイズ・名前・表示/非表示 |
chart.Chart | chartObject.getChart() | チャート本体。chartWizard() で構築し、型・データ源・タイトル・軸・系列を扱う | |
chart.ChartTitle | chart.getChartTitle() | チャート标题。setText() / getText() | |
chart.Axis | `chart.getAxes(enums.XlAxisType.Category\ | Value)` | 軸。目盛り・最大/最小・軸タイトル |
chart.Series | chart.getSeriesCollection(index) | 1 系列。getValues() / getXValues() / getPointSize() | |
chart.Legend | chart.getLegend() | 凡例。setPosition() / getPosition() |
WorkSheet 側のチャート操作メソッド:
| メソッド | 説明 |
|---|---|
addChartObject(name, left, top, width, height) | チャート枠を追加。位置・サイズはポイント(pt)単位 |
getChartObject(name) / getChartObject(index) | 名前 or 索引(1 始まり)で取得。範囲外は例外 |
deleteChartObject(name) / deleteChartObject(index) | 名前 or 索引で削除 |
コード
実行結果:
// charts.js — チャート(グラフ)の基本: 追加・タイトル・型・系列/軸の読み戻し・削除
const { nodeosbxl, enums } = require("nodeosbxl");
const app = new nodeosbxl.App();
const wb = app.createWorkBook("charts.xlsx");
const ws = wb.openWorkSheet("Sheet1");
// 補助: チャートタイプ数値 → enum 名
const chartTypeName = (code) =>
Object.keys(enums.XlChartType).find((k) => enums.XlChartType[k] === code) || String(code);
// 補助: シート上のチャート個数(getChartObject は範囲外で例外 → 数えて判定)
const countCharts = () => {
let n = 0;
for (;;) { try { ws.getChartObject(n + 1); n++; } catch (e) { break; } }
return n;
};
// 補助: チャートの系列数(getSeriesCollection は範囲外で例外)
const countSeries = (chart) => {
let n = 0;
for (;;) { try { chart.getSeriesCollection(n + 1); n++; } catch (e) { break; } }
return n;
};
// ---------- 1. データ表(2商品の月次売上)を作る ----------
["月", "商品A", "商品B"].forEach((h, c) => ws.getCells(1, c + 1).setValue(h));
const sales = [
["1月", 120, 90], ["2月", 135, 95], ["3月", 150, 110],
["4月", 142, 125], ["5月", 160, 118], ["6月", 175, 130],
];
sales.forEach((row, i) => {
ws.getCells(i + 2, 1).setValue(row[0]);
ws.getCells(i + 2, 2).setNumberValue(row[1]);
ws.getCells(i + 2, 3).setNumberValue(row[2]);
});
console.log("[1] データ表 A1:C7 を作成 / 商品A合計 =",
sales.reduce((s, r) => s + r[1], 0));
// ---------- 2. 集合縦棒グラフを追加(chartWizard)----------
// addChartObject(名前, left, top, width, height) — 位置・サイズはポイント(pt)単位
const co1 = ws.addChartObject("SalesColumn", 320, 10, 360, 220);
const chart1 = co1.getChart();
// chartWizard(source, type, plotBy, seriesLabelLines, categoryLabelLines,
// styleNo, colorNo, hasLegend, title)
chart1.chartWizard(
"Sheet1!A1:C7",
enums.XlChartType.ChartTypeColumnClustered,
enums.XlRowCol.Columns, // 系列を列方向に取る(商品A/商品B が 1 系列ずつ)
1, // seriesLabelLines: 先頭 1 行が系列名ヘッダ
1, // categoryLabelLines: 先頭 1 列がカテゴリ名ヘッダ
1, // chartStyleNo(1 始まり)
enums.XlChartColorPalette.XlPaletteColorful1,
true, // hasLegend: 凡例を表示
"月次売上" // title: 設定するとタイトルが表示される
);
console.log("[2] 型 =", chartTypeName(chart1.getChartType()),
"/ hasTitle =", chart1.hasTitle(),
"/ タイトル =", JSON.stringify(chart1.getChartTitle().getText()));
console.log(" データ源 =", chart1.getDataSource(),
"/ plotBy =", chart1.getPlotBy(),
"/ hasLegend =", chart1.hasLegend());
// ---------- 3. 系列・軸の読み戻し ----------
// 系列名を直接返す API は無い。系列名は chartWizard のヘッダ行なので、
// 個数は getSeriesCollection で数え、名前はヘッダセルから対応付けて確認する。
const n1 = countSeries(chart1);
console.log("[3] 系列数 =", n1);
for (let i = 1; i <= n1; i++) {
const s = chart1.getSeriesCollection(i);
const name = Object.values(ws.getCells(1, i + 1).getValue())[0]; // 系列 i → 列 i+1 のヘッダ
console.log(` 系列${i}「${name}」値 =`, JSON.stringify(s.getValues()),
"/ ポイント数 =", s.getPointSize());
}
console.log(" カテゴリ名 =",
JSON.stringify(chart1.getAxes(enums.XlAxisType.Category).getCategoryNames()));
// ---------- 4. 2つ目のグラフ(マーカー付き折れ線)+ 軸・凡例の設定 ----------
const co2 = ws.addChartObject("SalesLine", 320, 250, 360, 220);
const chart2 = co2.getChart();
chart2.chartWizard(
"Sheet1!A1:C7",
enums.XlChartType.ChartTypeLineMarkers,
enums.XlRowCol.Columns, 1, 1,
1, enums.XlChartColorPalette.XlPaletteColorful1, true); // hasLegend=true にしないと getLegend() が例外
// タイトルは setTitle(true) → getChartTitle().setText() でも設定できる
chart2.setTitle(true);
chart2.getChartTitle().setText("月次売上推移");
// 値軸: 最大/最小/主単位を固定(読み戻しは getMajorUnit と ...IsAuto 系)
const valAxis = chart2.getAxes(enums.XlAxisType.Value);
valAxis.setMaximumScale(200);
valAxis.setMinimumScale(0);
valAxis.setMajorUnit(50);
valAxis.setTitle(true);
valAxis.getTitle().setText("売上(万円)");
// 凡例を右へ
chart2.getLegend().setPosition(enums.XlLegendPosition.LegendPositionRight);
console.log("[4] 型 =", chartTypeName(chart2.getChartType()),
"/ タイトル =", JSON.stringify(chart2.getChartTitle().getText()));
console.log(" 値軸 主単位 =", valAxis.getMajorUnit(),
"/ 最大自動 =", valAxis.getMaximumScaleIsAuto(),
"/ 最小自動 =", valAxis.getMinimumScaleIsAuto());
console.log(" 値軸タイトル =", JSON.stringify(valAxis.getTitle().getText()),
"/ 凡例位置 =", chart2.getLegend().getPosition(),
`(Right=${enums.XlLegendPosition.LegendPositionRight})`);
// ---------- 5. チャート個数・位置・サイズの読み戻し ----------
console.log("[5] チャート個数 =", countCharts(),
"/ SalesColumn(left,top,width,height) =",
[co1.getLeft(), co1.getTop(), co1.getWidth(), co1.getHeight()].join(","));
// ---------- 6. チャートの削除 ----------
ws.deleteChartObject("SalesLine"); // 名前指定。deleteChartObject(2) のように索引(1始まり)でも可
console.log("[完了] 削除後のチャート個数 =", countCharts(),
"/ 残 =", ws.getChartObject(1).getName());
wb.save();
wb.close();
[1] データ表 A1:C7 を作成 / 商品A合計 = 882
[2] 型 = ChartTypeColumnClustered / hasTitle = true / タイトル = "月次売上"
データ源 = Sheet1!$A$1:$C$7 / plotBy = 2 / hasLegend = true
[3] 系列数 = 2
系列1「商品A」値 = ["120","135","150","142","160","175"] / ポイント数 = 6
系列2「商品B」値 = ["90","95","110","125","118","130"] / ポイント数 = 6
カテゴリ名 = ["1月","2月","3月","4月","5月","6月"]
[4] 型 = ChartTypeLineMarkers / タイトル = "月次売上推移"
値軸 主単位 = 50 / 最大自動 = false / 最小自動 = false
値軸タイトル = "売上(万円)" / 凡例位置 = 4 (Right=4)
[5] チャート個数 = 2 / SalesColumn(left,top,width,height) = 320,10,360,220
[完了] 削除後のチャート個数 = 1 / 残 = SalesColumn
解説
- 作成は 2 段階:
addChartObject()で枠を作り、getChart().chartWizard()で中身を構築する。addChartObject(name, left, top, width, height)が返すのは配置枠(ChartObject)だけで、 この時点のチャートは未構築です。chartObject.getChart()で得たChartに対してchartWizard()を呼んで初めて型・データが設定されます。
位置・サイズの単位はポイント(pt)です。 chartWizard()の引数順は Excel マクロと違うので注意。 シグネチャはchartWizard(source, chartType, plotBy, seriesLabelLines, categoryLabelLines, styleNo?, colorNo?, hasLegend?, title?, ...)。
sourceは"Sheet1!A1:C7"のような A1C1 形式、seriesLabelLines=1は「先頭 1 行が系列名」、categoryLabelLines=1は「先頭 1 列がカテゴリ名」を意味します。plotByは「系列をどの方向に取るか」。 上のように月を行・商品を列(B/C 列)に並べた表でenums.XlRowCol.Columns(=2) を渡すと、列ごとに 1 系列(商品A・商品B)になります(実測で 2 系列を確認)。- タイトルは 2 通りで設定できる。
chartWizard()のtitle引数に文字列を渡す(→hasTitle()がtrueになる)か、chart.setTitle(true)→chart.getChartTitle().setText("...")を呼ぶ方法です。
どちらもgetChartTitle().getText()で読み戻せます。 - 軸は
getAxes(enums.XlAxisType.Category|Value)で取る。 値軸の最大/最小はsetMaximumScale()/setMinimumScale()、 目盛りはsetMajorUnit()で設定します。
軸タイトルはaxis.setTitle(true)→axis.getTitle().setText()です。 - 系列の値は
getSeriesCollection(i).getValues()/getXValues()(どちらも文字列配列)で読み戻せる。 系列数そのものを返す API は無いため、上のサンプルはgetSeriesCollection()が例外を投げるまで数えています。
注意点
- チャートの見た目(色・凡例の実表示・折れ線の形など)はコンソールから検証できません。 このサンプルは型・タイトル文字列・系列の値・軸の設定値・個数といったプロパティの読み戻しで 正しく作れたかを確認しています。
最終的な見栄えは必ず Excel でcharts.xlsxを開いて目視確認してください。 - 未構築チャートへの
setChartType()/setDataSource()は例外になります。addChartObject()直後(chartWizard()前)のチャートに型やデータ源を設定しようとするとchart is not built例外が送出されます(セグメントフォルトはしない)。
必ずchartWizard()で構築してください。
無効なチャートタイプ値(-2や0、範囲外)もchartType is invalid例外で拒否されます。 getLegend()は凡例が有効なチャートでのみ取得できます。 凡例が無効のチャートではlegend not found例外になります。
有効化する方法は 2 つ: 構築時にchartWizard(…, hasLegend=true, …)を渡すか、後からchart.setLegend(true)を呼ぶ (実測:setLegend(true)後はgetLegend()/setPosition()とも正常。setLegend(false)で再び例外)。- 値軸の最大/最小を読み戻す getter はありません。
setMaximumScale()/setMinimumScale()に対応するgetMaximumScale()/getMinimumScale()は存在せず、getMaximumScaleIsAuto()/getMinimumScaleIsAuto()(boolean)で 「自動かどうか」しか確認できません。
手動設定後はfalseになります。
主単位はgetMajorUnit()で読み戻せます。 - 系列名(凡例の項目名)を返す API はありません。
SeriesにgetName()相当が無く、LegendEntryにもテキスト取得が無いため、 サンプルでは系列名を元表のヘッダセル(B1/C1)から読み出して対応付けています。 getValues()は数値セルを数値文字列で返し、文字列セルは空文字列""を返します(実測)。 グラフの系列値は数値が前提のため、文字列しか入っていないセルは""になります。
系列データはsetNumberValue()で数値として入れてください。- チャート個数を返す API は無く、
ws.getShapes().getCount()も使えません(typeofがundefined)。 個数はgetChartObject(1), getChartObject(2), ...が例外を投げるまで数える必要があります(サンプルのcountCharts())。 chartWizard()の省略可能引数は途中を飛ばせません。titleやhasLegendを渡したいなら、 その手前のstyleNo/colorNoにも値を与える必要があります(中間位置にundefined/nullを渡すと例外)。- 一部のチャート型は未対応。
enums.XlChartType.ChartTypeRegionMapはchartWizard()でunsupported例外になります。
関連
- 目次
- 前: 条件付き書式 / 次: ピボットテーブル
- 値と数式を入れて表を作る(チャート元データの作成) / 大量データの一括投入
- API リファレンス
ChartObject / Chart / ChartTitle / Axis / Series / Legend / XlChartType / XlRowCol / XlAxisType / XlLegendPosition