Web Components Excel 라이브러리 개요
Infragistics Web Components Excel 라이브러리를 사용하면 다음과 같은 친숙한 Microsoft® Excel® 스프레드시트 개체를 사용하여 스프레드시트 데이터로 작업할 수 있습니다 workbook
, Worksheet
, Cell
, Formula
그리고 더 많은. Infragistics Web Components Excel 라이브러리를 사용하면 응용 프로그램의 데이터를 Excel 스프레드시트에 쉽게 나타낼 수 있을 뿐만 아니라 Excel에서 응용 프로그램으로 데이터를 전송할 수 있습니다.
Web Components Excel 라이브러리 예제
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);
}
});
}
}
ts コピー import { ExcelUtility } from './ExcelUtility' ;
import { IgcExcelModule } from 'igniteui-webcomponents-excel' ;
import { Workbook } from 'igniteui-webcomponents-excel' ;
import { Worksheet } from 'igniteui-webcomponents-excel' ;
import { WorkbookFormat } from 'igniteui-webcomponents-excel' ;
import { ModuleManager } from 'igniteui-webcomponents-core' ;
ModuleManager.register(
IgcExcelModule
);
export class ExcelLibraryOverview {
public canSave = false ;
public wb: Workbook;
public ws: Worksheet;
public worksheetRegion: string [] | null ;
public selectedRegion: string | null ;
constructor ( ) {
this .init();
const saveWorkbook = document .getElementById('saveWorkbook' );
saveWorkbook!.addEventListener('click' , this .onClick);
}
public workbookSave(): void {
if (this .canSave) {
ExcelUtility.save(this .wb, 'ExcelWorkbook' ).then((f: any ) => {
console .log('Saved:' + f);
}, (e: any ) => {
console .error('ExcelUtility.Save Error:' + e);
});
}
}
public workbookParse(wb: Workbook): void {
if (wb === undefined ) {
this .worksheetRegion = null ;
this .selectedRegion = null ;
} else {
const names = new Array <string >();
const worksheets = wb.worksheets();
const wsCount = worksheets.count;
for (let i = 0 ; i < wsCount; i ++) {
const tables = worksheets.item(i).tables();
const tCount = tables.count;
for (let j = 0 ; j < tCount; j++) {
names.push(worksheets.item(i).name + ' - ' + tables.item(j).name);
}
}
this .worksheetRegion = names;
this .selectedRegion = names.length > 0 ? names[0 ] : null ;
}
this .wb = wb;
this .canSave = wb !== null ;
}
public workbookCreate(): void {
const wb = new Workbook(WorkbookFormat.Excel2007);
const employeeSheet = wb.worksheets().add('Employees' );
const employeeHeader = employeeSheet.rows(0 );
const companies = ['Amazon' , 'Ford' , 'Jaguar' , 'Tesla' , 'IBM' , 'Microsoft' ];
const firstNames = ['Andrew' , 'Mike' , 'Martin' , 'Ann' , 'Victoria' , 'John' , 'Brian' , 'Jason' , 'David' ];
const lastNames = ['Smith' , 'Jordan' , 'Johnson' , 'Anderson' , 'Louis' , 'Phillips' , 'Williams' ];
const countries = ['UK' , 'France' , 'USA' , 'Germany' , 'Poland' , 'Brazil' ];
const titles = ['Sales Rep.' , 'Engineer' , 'Administrator' , 'Manager' ];
const employeeColumns = ['Name' , 'Company' , 'Title' , 'Age' , 'Country' ];
for (let col = 0 ; col < employeeColumns.length; col++) {
employeeSheet.columns(col).width = 5000 ;
employeeHeader.setCellValue(col, employeeColumns[col]);
}
for (let i = 1 ; i < 20 ; i++) {
const company = this .getItem(companies);
const title = this .getItem(titles);
const country = this .getItem(countries);
const name = this .getItem(firstNames) + ' ' + this .getItem(lastNames);
const salary = this .getRandom(45000 , 95000 );
const age = this .getRandom(20 , 65 );
const wr = employeeSheet.rows(i);
wr.setCellValue(0 , name);
wr.setCellValue(1 , company);
wr.setCellValue(2 , title);
wr.setCellValue(3 , age);
wr.setCellValue(4 , country);
wr.setCellValue(5 , salary);
}
const expanseSheet = wb.worksheets().add('Expanses' );
const expanseHeader = expanseSheet.rows(0 );
const expanseNames = ['Year' , 'Computers' , 'Research' , 'Travel' , 'Salary' , 'Software' ];
let expanseCol = 0 ;
for (const key of expanseNames) {
expanseSheet.columns(expanseCol).width = 5000 ;
expanseHeader.setCellValue(expanseCol, key);
for (let i = 1 ; i < 20 ; i++) {
const wr = expanseSheet.rows(i);
if (key === 'Year' ) {
wr.setCellValue(expanseCol, 2010 + i);
} else if (key === 'Computers' ) {
wr.setCellValue(expanseCol, this .getAmount(50000 , 65000 ));
} else if (key === 'Research' ) {
wr.setCellValue(expanseCol, this .getAmount(150000 , 165000 ));
} else if (key === 'Travel' ) {
wr.setCellValue(expanseCol, this .getAmount(20000 , 25000 ));
} else if (key === 'Salary' ) {
wr.setCellValue(expanseCol, this .getAmount(4000000 , 450000 ));
} else if (key === 'Software' ) {
wr.setCellValue(expanseCol, this .getAmount(100000 , 150000 ));
}
}
expanseCol++;
}
const incomeSheet = wb.worksheets().add('Income' );
const incomeHeader = incomeSheet.rows(0 );
const incomeNames = ['Year' , 'Phones' , 'Computers' , 'Software' , 'Services' , 'Royalties' ];
let incomeCol = 0 ;
for (const key of incomeNames) {
incomeSheet.columns(incomeCol).width = 5000 ;
incomeHeader.setCellValue(incomeCol, key);
for (let i = 1 ; i < 20 ; i++) {
const wr = incomeSheet.rows(i);
if (key === 'Year' ) {
wr.setCellValue(incomeCol, 2010 + i);
} else if (key === 'Software' ) {
wr.setCellValue(incomeCol, this .getAmount(700000 , 850000 ));
} else if (key === 'Computers' ) {
wr.setCellValue(incomeCol, this .getAmount(250000 , 265000 ));
} else if (key === 'Royalties' ) {
wr.setCellValue(incomeCol, this .getAmount(400000 , 450000 ));
} else if (key === 'Phones' ) {
wr.setCellValue(incomeCol, this .getAmount(6000000 , 650000 ));
} else if (key === 'Services' ) {
wr.setCellValue(incomeCol, this .getAmount(700000 , 750000 ));
}
}
incomeCol++;
}
this .workbookParse(wb);
}
public getRandom(min: number , max : number ): number {
return Math .floor(Math .random() * (max - min + 1 ) + min);
}
public getItem(array: string []): string {
const i = this .getRandom(0 , array.length - 1 );
return array[i];
}
public getAmount (min: number , max: number ) {
const n = this .getRandom(min, max);
const s = n.toFixed(2 ).replace(/\d(?=(\d{3})+\.)/g , '$&,' );
return s;
}
public onClick = (e: any ) => {
this .workbookSave();
}
public init ( ) {
this .workbookCreate();
}
}
new ExcelLibraryOverview();
ts コピー <!DOCTYPE html >
<html >
<head >
<title > ExcelLibraryOverview</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" >
<button id ="saveWorkbook" > Save Workbook</button >
</div >
</div >
<% if (false) { %><script src ="src/index.ts" > </script > <% } %>
</body >
</html >
html コピー
이 샘플이 마음에 드시나요? 당사의 완전한 Ignite UI for Web Components 툴킷에 액세스하여 몇 분 만에 나만의 앱을 빌드하기 시작하세요. 무료로 다운로드하세요.
종속성
엑셀 패키지 설치 시 코어 패키지도 함께 설치해야 합니다.
npm install --save igniteui-webcomponents-core
npm install --save igniteui-webcomponents-excel
cmd
컴포넌트 모듈
Web Components Excel 라이브러리에는 다음 모듈이 필요합니다.
import { ModuleManager } from 'igniteui-webcomponents-core' ;
import { IgcExcelModule } from 'igniteui-webcomponents-excel' ;
ModuleManager.register(
IgcExcelModule
);
ts
모듈 구현
Excel 라이브러리에는 앱의 번들 크기를 제한하는 데 사용할 수 있는 5개의 모듈이 포함되어 있습니다.
IgxExcelCoreModule – 여기에는 개체 모델과 Excel 인프라의 대부분이 포함되어 있습니다.
IgxExcelFunctionsModule – 여기에는 Sum, Average, Min, Max 등과 같은 수식 평가를 위한 대부분의 함수가 포함되어 있습니다. 이 모듈이 없어도 수식을 계산할 경우 수식 구문 분석에 문제가 발생하지 않습니다. 예를 들어 “=SUM(A1:A5)”와 같은 수식을 적용하고 셀의 값을 요청하면 #NAME!이 표시됩니다. 오류가 반환되었습니다. 이는 예외 발생이 아닙니다. 수식으로 인해 오류가 발생할 수 있으므로 특정 오류를 나타내는 개체입니다.
IgxExcelXlsModule – 여기에는 xls(및 관련) 유형 파일, 즉 Excel97to2003 관련 WorkbookFormats에 대한 로드 및 저장 논리가 포함되어 있습니다.
IgxExcelXlsxModule – 여기에는 xlsx(및 관련) 유형 파일, 즉 Excel2007 관련 및 StrictOpenXml WorkbookFormats에 대한 로드 및 저장 논리가 포함되어 있습니다.
IgxExcelModule – 이는 다른 4개의 모듈을 참조하므로 기본적으로 모든 기능이 로드/사용 가능하도록 보장합니다.
지원되는 Microsoft Excel 버전
다음은 지원되는 Excel 버전 목록입니다.**
마이크로소프트 엑셀 97
마이크로소프트 엑셀 2000
마이크로소프트 엑셀 2002
마이크로소프트 엑셀 2003
마이크로소프트 엑셀 2007
마이크로소프트 엑셀 2010
마이크로소프트 엑셀 2013
마이크로소프트 엑셀 2016
통합 문서 로드 및 저장
이제 Excel 라이브러리 모듈을 가져왔으므로 다음 단계는 통합 문서를 로드하는 것입니다.
다음 코드 조각에서는 외부 Excel유틸리티 클래스는 저장하고 로드하는 데 사용됩니다. workbook
.
통합 workbook
개체를 로드하고 저장하려면 실제 workbook
개체의 저장 메서드와 정적 Load
메서드를 활용할 수 있습니다.
import { Workbook } from "igniteui-webcomponents-excel" ;
import { WorkbookSaveOptions } from "igniteui-webcomponents-excel" ;
import { WorkbookFormat } from "igniteui-webcomponents-excel" ;
import { ExcelUtility } from "ExcelUtility" ;
var workbook = ExcelUtility.load(file);
ExcelUtility.save(workbook, "fileName" );
ts
API 참조