Web Components チャートの使用
Infragistics Web Components Excel Engine の WorksheetChart
機能は、ワークシートのセル領域全体のデータ トレンドをチャートで表示します。たとえば Excel データを縦棒チャートや折れ線チャートで可視化する場合に便利です。
Web Components チャートの使用の例
import { saveAs } from "file-saver";
import { Workbook } from 'igniteui-webcomponents-excel';
import { WorkbookFormat } from 'igniteui-webcomponents-excel';
import { WorkbookSaveOptions } from 'igniteui-webcomponents-excel';
import { WorkbookLoadOptions } from 'igniteui-webcomponents-excel';
import { IgcExcelXlsxModule } from 'igniteui-webcomponents-excel';
import { IgcExcelCoreModule } from 'igniteui-webcomponents-excel';
import { IgcExcelModule } from 'igniteui-webcomponents-excel';
IgcExcelCoreModule.register();
IgcExcelModule.register();
IgcExcelXlsxModule.register();
export class ExcelUtility {
public static getExtension(format: WorkbookFormat) {
switch (format) {
case WorkbookFormat.StrictOpenXml:
case WorkbookFormat.Excel2007:
return ".xlsx";
case WorkbookFormat.Excel2007MacroEnabled:
return ".xlsm";
case WorkbookFormat.Excel2007MacroEnabledTemplate:
return ".xltm";
case WorkbookFormat.Excel2007Template:
return ".xltx";
case WorkbookFormat.Excel97To2003:
return ".xls";
case WorkbookFormat.Excel97To2003Template:
return ".xlt";
}
}
public static load(file: File): Promise<Workbook> {
return new Promise<Workbook>((resolve, reject) => {
ExcelUtility.readFileAsUint8Array(file).then((a) => {
Workbook.load(a, new WorkbookLoadOptions(), (w) => {
resolve(w);
}, (e) => {
reject(e);
});
}, (e) => {
reject(e);
});
});
}
public static loadFromUrl(url: string): Promise<Workbook> {
return new Promise<Workbook>((resolve, reject) => {
const req = new XMLHttpRequest();
req.open("GET", url, true);
req.responseType = "arraybuffer";
req.onload = (d) => {
const data = new Uint8Array(req.response);
Workbook.load(data, new WorkbookLoadOptions(), (w) => {
resolve(w);
}, (e) => {
reject(e);
});
};
req.send();
});
}
public static save(workbook: Workbook, fileNameWithoutExtension: string): Promise<string> {
return new Promise<string>((resolve, reject) => {
const opt = new WorkbookSaveOptions();
opt.type = "blob";
workbook.save(opt, (d) => {
const fileExt = ExcelUtility.getExtension(workbook.currentFormat);
const fileName = fileNameWithoutExtension + fileExt;
saveAs(d as Blob, fileName);
resolve(fileName);
}, (e) => {
reject(e);
});
});
}
private static readFileAsUint8Array(file: File): Promise<Uint8Array> {
return new Promise<Uint8Array>((resolve, reject) => {
const fr = new FileReader();
fr.onerror = (e) => {
reject(fr.error);
};
if (fr.readAsBinaryString) {
fr.onload = (e) => {
const rs = (fr as any).resultString;
const str: string = rs != null ? rs : fr.result;
const result = new Uint8Array(str.length);
for (let i = 0; i < str.length; i++) {
result[i] = str.charCodeAt(i);
}
resolve(result);
};
fr.readAsBinaryString(file);
} else {
fr.onload = (e) => {
resolve(new Uint8Array(fr.result as ArrayBuffer));
};
fr.readAsArrayBuffer(file);
}
});
}
}
tsimport { ExcelUtility } from './ExcelUtility';
// import { IgcExcelXlsxModule } from 'igniteui-webcomponents-excel';
// import { IgcExcelCoreModule } from 'igniteui-webcomponents-excel';
import { IgcExcelModule } from 'igniteui-webcomponents-excel';
import { IgcDataGridModule } from 'igniteui-webcomponents-grids';
import { IgcDataGridComponent } from 'igniteui-webcomponents-grids';
import { IgcCategoryChartModule } from 'igniteui-webcomponents-charts';
import { IgcCategoryChartComponent } from 'igniteui-webcomponents-charts';
import { Workbook } from 'igniteui-webcomponents-excel';
import { WorkbookFormat, WorksheetRegion } from 'igniteui-webcomponents-excel';
import { ChartType } from 'igniteui-webcomponents-excel';
import { AxisType } from 'igniteui-webcomponents-excel';
import { ModuleManager } from 'igniteui-webcomponents-core';
ModuleManager.register(
// IgcExcelXlsxModule,
// IgcExcelCoreModule,
IgcExcelModule,
IgcDataGridModule,
IgcCategoryChartModule
);
export class ExcelLibraryCharts {
public excelData: any[] = [];
public chartData: any[] = [];
constructor() {
this.initData();
const chart = document.getElementById('chart') as IgcCategoryChartComponent;
chart.dataSource = this.chartData;
const grid = document.getElementById('grid') as IgcDataGridComponent;
grid.dataSource = this.excelData;
const button = document.getElementById('export') as HTMLButtonElement;
button!.addEventListener('click', this.exportData);
}
public initData() {
const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
const groups = ['Heating', 'Electricity', 'Water', 'Taxes'];
const expanseKey = 'Expense';
const monthKey = 'Month';
const data = new Array<any>();
// generating excel data source
for (const group of groups) {
const r = {};
r[expanseKey] = group;
let index = 0;
for (const month of months) {
const x = index * 15 * Math.PI / 180;
const rand = this.getRandom(50, 100);
const heat = Math.abs(Math.cos(x)) * 300 + rand;
const ac = Math.abs(Math.sin(x)) * 500 + rand;
if (group === 'Heating') {
r[month] = Math.round(heat);
} else if (group === 'Electricity') {
r[month] = Math.round(ac);
} else if (group === 'Water') {
r[month] = this.getRandom(100, 150);
} else if (group === 'Taxes') {
r[month] = this.getRandom(700, 800);
}
index = index + 1;
}
data.push(r);
}
this.excelData = data;
// since we will export the data transposed (plotByRows will be true)
// if we want to show the data that way in the ui then we need a transposed
// version of the data for the category chart to bind to
const chartData = new Array<any>();
for (const month of months) {
const r = {};
r[monthKey] = month;
for (const item of data) {
r[item[expanseKey]] = item[month];
}
chartData.push(r);
}
this.chartData = chartData;
}
public getRandom(min: number, max: number): number {
return Math.floor(Math.random() * (max - min + 1) + min);
}
public exportData = (e: any) => {
const headers = Object.keys(this.excelData[0]);
headers.pop();
const wb = new Workbook(WorkbookFormat.Excel2007);
const ws = wb.worksheets().add('Sheet1');
ws.defaultColumnWidth = 200 * 20;
// reserving the [0] row where we will place the chart shape
// the [1] will be the headers. so data will start on [2]
const firstDataRow = 2;
const headerRow = ws.rows(firstDataRow - 1);
for (let c = 0; c < headers.length; c++) {
headerRow.setCellValue(c, headers[c]);
}
for (let r = 0; r < this.excelData.length; r++) {
const xlRow = ws.rows(r + firstDataRow);
const dataRow = this.excelData[r];
for (let c = 0; c < headers.length; c++) {
xlRow.setCellValue(c, dataRow[headers[c]]);
}
}
const indexRow = firstDataRow - 1;
const indexData = firstDataRow + this.excelData.length - 1;
const indexHeader = headers.length - 1;
const tableRegion = new WorksheetRegion(ws, indexRow, 0, indexData, indexHeader);
const table = ws.tables().add(tableRegion.toString(), true);
// set some extra height for the row where the chart will be
ws.rows(0).height = 5000;
const chart = ws.shapes().addChart(ChartType.ColumnClustered,
ws.rows(0).cells(0), { x: 0, y: 0 },
ws.rows(0).cells(headers.length - 1), { x: 100, y: 100 });
chart.setSourceData(table.wholeTableRegion.toString(), true);
chart.axisCollection(AxisType.Category).axisBetweenCategories = true;
ExcelUtility.save(wb, 'chartSample');
}
}
new ExcelLibraryCharts();
ts<!DOCTYPE html>
<html>
<head>
<title>ExcelLibraryCharts</title>
<meta charset="UTF-8" />
<link rel="shortcut icon" href="https://static.infragistics.com/xplatform/images/browsers/wc.png" >
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons" />
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Kanit&display=swap" />
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Titillium Web" />
<link rel="stylesheet" href="https://static.infragistics.com/xplatform/css/samples/shared.v8.css" type="text/css" />
</head>
<body>
<div id="root">
<div class="container sample">
<div class="options horizontal">
<button class="options-label" id="export">Export</button>
</div>
<div style="height: calc(100% - 3rem)">
<igc-category-chart id="chart"
height="50%" width="100%"
y-axis-minimum-value="0"
x-axis-interval="1"
chart-type="column"
brushes="#4f81bd, #c0504d, #9bbb59, #8064a2"
outlines="#4f81bd, #c0504d, #9bbb59, #8064a2"
thickness="0">
</igc-category-chart>
<igc-data-grid id="grid"
height="50%"
width="100%"
auto-generate-columns="false">
<igc-text-column field="Expense"></igc-text-column>
<igc-numeric-column field="Jan"></igc-numeric-column>
<igc-numeric-column field="Feb"></igc-numeric-column>
<igc-numeric-column field="Mar"></igc-numeric-column>
<igc-numeric-column field="Apr"></igc-numeric-column>
<igc-numeric-column field="May"></igc-numeric-column>
<igc-numeric-column field="Jun"></igc-numeric-column>
<igc-numeric-column field="Jul"></igc-numeric-column>
<igc-numeric-column field="Aug"></igc-numeric-column>
<igc-numeric-column field="Sep"></igc-numeric-column>
<igc-numeric-column field="Oct"></igc-numeric-column>
<igc-numeric-column field="Nov"></igc-numeric-column>
<igc-numeric-column field="Dec"></igc-numeric-column>
</igc-data-grid>
</div>
</div>
</div>
<!-- This script is needed only for parcel and it will be excluded for webpack -->
<% if (false) { %><script src="src/index.ts"></script><% } %>
</body>
</html>
html/* shared styles are loaded from: */
/* https://static.infragistics.com/xplatform/css/samples */
css
このサンプルが気に入りましたか? 完全な Ignite UI for Web Componentsツールキットにアクセスして、すばやく独自のアプリの作成を開始します。無料でダウンロードできます。
使用方法
ワークシートを追加するには、ワークシートの Shapes コレクションの AddChart
メソッドを使用します。このメソッドは、チャート タイプと表示位置を左上のセル、右下のセル、それらのセルのパーセンテージで指定できます。
AddChart
メソッドはワークシートに追加されるワークシート チャート要素を返します。次にチャートの setSourceData
メソッドを使用してデータ ソースとして使用するワークシート セル領域のセルのセル アドレスを設定できます。同様に行列のマッピングを Y と X 軸に切り替えることもできます。
Line
、Area
、IgcColumnComponent
、Pie
を含む 70 タイプ以上のチャート タイプがサポートされます。
以下のコードは、Excel チャート機能を有効にする方法を示します。以下のスニペットは、ワークシートの最初の行の最初のセルと 13 番目のセル間に縦棒チャートを追加します。ソースデータは A2:M6 領域のデータに設定します。縦棒チャートの X と Y 軸の列と行のマッピングを切り替えます。
var chart = ws.shapes().addChart(ChartType.ColumnClustered,
ws.rows(0).cells(0), { x: 0, y: 0 },
ws.rows(0).cells(12), { x: 100, y: 100 });
chart.setSourceData("A2:M6", true);
ts
API リファレンス
AddChart
Area
IgcColumnComponent
Line
Pie
WorksheetChart