Angular 차트 작업
Infragistics Angular Excel Engine의 WorksheetChart
기능을 사용하면 워크시트의 셀 영역에 걸쳐 데이터 추세를 시각적 차트로 표현할 수 있습니다. 예를 들어, 셀 영역에 있는 Excel 데이터를 열, 선 또는 70개 이상의 다른 차트 유형으로 시각화하려는 경우 이 기능을 사용하면 이를 달성하는 데 도움이 될 수 있습니다.
60 以上のリアルタイム Angular チャート を使用して、何百万ものデータ ポイントを描画し、視覚化を構築します。これは、あらゆるアプリケーション シナリオに対応する最も広範なチャート ライブラリです。
Angular 차트 작업 예제
import { saveAs } from "file-saver";
import { Workbook } from "igniteui-angular-excel";
import { WorkbookFormat } from "igniteui-angular-excel";
import { WorkbookSaveOptions } from "igniteui-angular-excel";
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, null, (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, null, (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 { NgModule } from "@angular/core";
import { FormsModule } from "@angular/forms";
import { CommonModule } from "@angular/common";
import { BrowserModule } from "@angular/platform-browser";
import { BrowserAnimationsModule } from "@angular/platform-browser/animations";
import { AppComponent } from "./app.component";
import { IgxGridModule } from "igniteui-angular";
import { IgxCategoryChartModule } from "igniteui-angular-charts";
import { IgxExcelModule } from "igniteui-angular-excel";
@NgModule({
bootstrap: [AppComponent],
declarations: [
AppComponent,
],
imports: [
BrowserModule,
BrowserAnimationsModule,
CommonModule,
FormsModule,
IgxGridModule,
IgxCategoryChartModule,
IgxExcelModule
],
providers: [],
schemas: []
})
export class AppModule {}
tsimport { AfterViewInit, ChangeDetectionStrategy, Component } from "@angular/core";
import { AxisType } from "igniteui-angular-excel";
import { ChartType } from "igniteui-angular-excel";
import { Workbook } from "igniteui-angular-excel";
import { WorkbookFormat } from "igniteui-angular-excel";
import { WorksheetRegion } from "igniteui-angular-excel";
import { ExcelUtility } from "./ExcelUtility";
@Component({
standalone: false,
changeDetection: ChangeDetectionStrategy.OnPush,
selector: "app-root",
styleUrls: ["./app.component.scss"],
templateUrl: "./app.component.html"
})
export class AppComponent implements AfterViewInit {
public excelData: any[];
public chartData: any[];
constructor() {
this.initializeData();
}
public initializeData() {
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() {
const headers = Object.keys(this.excelData[0]);
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");
}
public ngOnInit() {
}
public ngAfterViewInit(): void {
}
}
ts<div class="container">
<div class="options">
<button (click)="exportData()">Export To Excel File</button>
</div>
<div class="chart">
<igx-category-chart #chart
height="60%" width="100%"
yAxisMinimumValue=0
xAxisInterval=1
chartType="column"
brushes="#4f81bd, #c0504d, #9bbb59, #8064a2"
outlines="#4f81bd, #c0504d, #9bbb59, #8064a2"
thickness=0
[dataSource]="chartData">
</igx-category-chart>
<igx-grid [data]="excelData" height="40%" width="100%" [autoGenerate]="false">
<igx-column [field]="'Expense'" [resizable]="true" width="10%"></igx-column>
<igx-column [field]="'Jan'" [resizable]="true" width="7.5%"></igx-column>
<igx-column [field]="'Feb'" [resizable]="true" width="7.5%"></igx-column>
<igx-column [field]="'Mar'" [resizable]="true" width="7.5%"></igx-column>
<igx-column [field]="'Apr'" [resizable]="true" width="7.5%"></igx-column>
<igx-column [field]="'May'" [resizable]="true" width="7.5%"></igx-column>
<igx-column [field]="'Jun'" [resizable]="true" width="7.5%"></igx-column>
<igx-column [field]="'Jul'" [resizable]="true" width="7.5%"></igx-column>
<igx-column [field]="'Aug'" [resizable]="true" width="7.5%"></igx-column>
<igx-column [field]="'Sep'" [resizable]="true" width="7.5%"></igx-column>
<igx-column [field]="'Oct'" [resizable]="true" width="7.5%"></igx-column>
<igx-column [field]="'Nov'" [resizable]="true" width="7.5%"></igx-column>
<igx-column [field]="'Dec'" [resizable]="true" width="7.5%"></igx-column>
</igx-grid>
</div>
</div>
html.container {
display: flex;
flex-flow: column;
height: 100%;
min-width: 300px;
}
.chart {
flex: 1;
overflow: hidden;
}
scss
이 샘플이 마음에 드시나요? 전체 Ignite UI for Angular 툴킷에 액세스하고 몇 분 안에 나만의 앱을 구축해 보세요. 무료로 다운로드하세요.
용법
워크시트에 차트를 추가하려면 워크시트 도형 컬렉션의 AddChart
메서드를 사용해야 합니다. 이 방법에서는 사용하려는 차트 유형, 왼쪽 상단 셀, 오른쪽 하단 셀 및 차트가 차지할 셀의 비율을 지정할 수 있습니다.
AddChart
메서드는 워크시트에 추가할 워크시트 차트 요소를 반환합니다. 이 정보가 있으면 차트의 setSourceData
메소드를 사용하여 데이터 소스로 사용하려는 워크시트 셀 영역의 셀 주소를 설정할 수 있을 뿐만 아니라 열과 매핑을 전환할지 여부도 설정할 수 있습니다. X 및 Y축에 행을 추가합니다.
다음을 포함하여 70개 이상의 지원되는 차트 유형이 있습니다 Line
, Area
, IgxColumnComponent
그리고 Pie
.
다음 코드는 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
IgxColumnComponent
Line
Pie
WorksheetChart