React ワークブックの使用
Infragistics React Excel Engine は、データを Microsoft® Excel® に保存、また Microsoft® Excel® からの読み込みを可能にします。ライブラリのさまざまなクラスを使用してワークブックやワークシートを作成、データを入力、データを Excel にエクスポートできます。Infragistics React Excel Engine は、Excel スプレッドシートでアプリケーションのデータの表示や Excel からアプリケーションへのデータのインポートが簡単にできます。
React ワークブックの使用の例
import { saveAs } from "file-saver" ;
import { Workbook } from "@infragistics/igniteui-react-excel" ;
import { WorkbookFormat } from "@infragistics/igniteui-react-excel" ;
import { WorkbookSaveOptions } from "@infragistics/igniteui-react-excel" ;
import { WorkbookLoadOptions } from "@infragistics/igniteui-react-excel" ;
import { IgrExcelXlsxModule } from "@infragistics/igniteui-react-excel" ;
import { IgrExcelCoreModule } from "@infragistics/igniteui-react-excel" ;
import { IgrExcelModule } from "@infragistics/igniteui-react-excel" ;
IgrExcelCoreModule.register();
IgrExcelModule.register();
IgrExcelXlsxModule.register();
export class ExcelUtility {
public static getExtension(format: WorkbookFormat): string {
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): void => {
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): void => {
reject(fr.error);
};
if (fr.readAsBinaryString) {
fr.onload = (e): void => {
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): void => {
resolve(new Uint8Array (fr.result as ArrayBuffer ));
};
fr.readAsArrayBuffer(file);
}
});
}
}
ts コピー import React from 'react' ;
import ReactDOM from 'react-dom/client' ;
import './index.css' ;
import { IgrDataGridModule } from "@infragistics/igniteui-react-grids" ;
import { IgrDataGrid } from "@infragistics/igniteui-react-grids" ;
import { Workbook } from "@infragistics/igniteui-react-excel" ;
import { WorkbookFormat } from "@infragistics/igniteui-react-excel" ;
import { WorksheetRegion } from "@infragistics/igniteui-react-excel" ;
import { ExcelUtility } from './ExcelUtility' ;
IgrDataGridModule.register();
export default class ExcelLibraryUsingWorkbooks extends React.Component <any, any> {
public grid: IgrDataGrid;
public employeeData: any [];
public expenseData: any [];
public incomeData: any [];
public companies: string [];
public firstNames: string [];
public lastNames: string [];
public countries: string [];
public titles: string [];
public employeeColumns: string [];
constructor (props: any ) {
super (props);
this .onGridRef = this .onGridRef.bind(this );
this .createWorkbook = this .createWorkbook.bind(this );
this .saveWorkbook = this .saveWorkbook.bind(this );
this .switchDataSource = this .switchDataSource.bind(this );
this .companies = ["Amazon" , "Ford" , "Jaguar" , "Tesla" , "IBM" , "Microsoft" ];
this .firstNames = ["Andrew" , "Mike" , "Martin" , "Ann" , "Victoria" , "John" , "Brian" , "Jason" , "David" ];
this .lastNames = ["Smith" , "Jordan" , "Johnson" , "Anderson" , "Louis" , "Phillips" , "Williams" ];
this .countries = ["UK" , "France" , "USA" , "Germany" , "Poland" , "Brazil" ];
this .titles = ["Sales Rep." , "Engineer" , "Administrator" , "Manager" ];
this .employeeColumns = ["Name" , "Company" , "Title" , "Age" , "Country" , "Salary" ];
this .initData();
this .state = {
selected: "Employees - Table1"
} as any ;
}
public render (): JSX .Element {
return (
<div className ="container sample" >
<div className ="options horizontal" >
<button className ="options-button" onClick ={this.createWorkbook} > Create Workbook</button >
<button className ="options-button" onClick ={this.saveWorkbook} > Save Workbook</button >
<label className ="options-label" > Select Table to Export: </label >
<select onChange ={this.onTableChange} value ={(this.state as any ).selected }>
<option > Employees - Table1</option >
<option > Expenses - Table2</option >
<option > Income - Table3</option >
</select >
</div >
<div className ="container" >
<IgrDataGrid
ref = {this.onGridRef}
height ="100%"
width ="100%"
dataSource ={this.employeeData} />
</div >
</div >
);
}
public initData() {
this .expenseData = [];
this .employeeData = [];
this .incomeData = [];
const startYear = 2011 ;
for (let i = 1 ; i < 20; i++) {
const year = startYear + i;
// Employee Data
const name: string = this.getItem(this.firstNames) + " " + this.getItem(this.lastNames);
const company: string = this.getItem(this.companies);
const title: string = this.getItem(this.titles);
const age: number = this.getRandom(25, 60);
const country: string = this.getItem(this.countries);
const salary: string = this.getAmount(60000, 80000);
// Expense Data
const computerExpense: string = this.getAmount(50000, 60000);
const researchExpense: string = this.getAmount(120000, 160000);
const travelExpense: string = this.getAmount(15000, 25000);
const salaryExpense: string = this.getAmount(1000000, 2000000);
const softwareExpense: string = this.getAmount(100000, 150000);
// Income Data
const phoneIncome: string = this.getAmount(3500000, 6000000);
const computerIncome: string = this.getAmount(200000, 300000);
const softwareIncome: string = this.getAmount(700000, 800000);
const serviceIncome: string = this.getAmount(650000, 750000);
const royaltyIncome: string = this.getAmount(400000, 450000);
this.employeeData.push({
"Name": name,
"Company": company,
"Title": title,
"Age": age,
"Country": country,
"Salary": salary
});
this.expenseData.push({
"Year": year,
"Computers": computerExpense,
"Research": researchExpense,
"Travel": travelExpense,
"Salary": salaryExpense,
"Software": softwareExpense
});
this.incomeData.push({
"Year": year,
"Phones": phoneIncome,
"Computers": computerIncome,
"Software": softwareIncome,
"Services": serviceIncome,
"Royalties": royaltyIncome
});
}
}
public getItem(array: string[]): string {
const i = this.getRandom(0, array.length - 1);
return array[i];
}
public getRandom(min: number, max: number): number {
return Math.floor(Math.random() * (max - min + 1) + min);
}
public getAmount(min: number, max: number) {
const n = this.getRandom(min, max);
const s = n.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, "$&,");
return "$" + s.replace(".00", "");
}
public onGridRef(grid: IgrDataGrid) {
if (!grid) { return; }
this.grid = grid;
}
public onTableChange = (e: any) => {
const newVal : string = e.target.value.toString();
this .setState({selected: newVal} as any );
this .switchDataSource(newVal);
}
public createWorkbook() {
this .initData();
this .switchDataSource((this .state as any ).selected);
}
public saveWorkbook() {
const headers = Object.keys(this .grid.dataSource[0 ]);
headers.pop();
const wb = new Workbook(WorkbookFormat.Excel2007);
const ws = wb.worksheets().add("Sheet1" );
for (let i =0 ; i<headers.length; i++){
ws.rows(0).cells(i).value = headers[i];
}
for(let i=0; i <this.grid.dataSource.length; i++){
const dataRow = this.grid.dataSource[i];
const xlRow = ws.rows(i + 1);
for(let j=0; j<headers.length; j++){
xlRow.setCellValue(j, dataRow[headers[j]]);
}
}
ExcelUtility.save(wb, "WorkbookSample");
}
public switchDataSource(value: string){
if(value.includes("Employee")){
// this.setState({data: this.employeeData} as any);
this.grid.dataSource = this.employeeData;
}
else if(value.includes("Expense")){
// this.setState({data: this.expenseData} as any);
this.grid.dataSource = this.expenseData;
}
else{
// this.setState({data: this.incomeData} as any);
this.grid.dataSource = this.incomeData;
}
}
}
// rendering above class to the React DOM
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<ExcelLibraryUsingWorkbooks /> );
tsx コピー
このサンプルが気に入りましたか? 完全な Ignite UI for Reactツールキットにアクセスして、すばやく独自のアプリの作成を開始します。無料でダウンロードできます。
既定のフォントを変更
IWorkbookFont
の新しいインスタンスを作成します。Workbook
の styles
コレクションに新しいフォントを追加します。このスタイルにはワークブックのすべてのセルのデフォルトのプロパティが含まれています。ただし、行、列またはセルで指定されている場合はその限りではありません。スタイルのプロパティを変更すると、ワークブックのデフォルトのセル書式プロパティが変更します。
var workbook = new Workbook();
var font: IWorkbookFont;
font = workbook.styles().normalStyle.styleFormat.font;
font.name = "Times New Roman" ;
font.height = 16 * 20 ;
ts
ワークブック プロパティの設定
Microsoft Excel® ドキュメント プロパティは、ドキュメントの整理やトラッキングを改善するための情報を提供します。Workbook
オブジェクトの documentProperties
プロパティを使用してこれらのプロパティを設定するために、Infragistics React Excel Engine を使用できます。使用可能なプロパティは以下のとおりです。
Author
Title
Subject
Keywords
Category
Status
Comments
Company
Manager
以下のコードは、ブックを作成し、title
および status
ドキュメント プロパティを設定する方法を示します。
var workbook = new Workbook();
workbook.documentProperties.title = "Expense Report" ;
workbook.documentProperties.status = "Complete" ;
ts
ブックの保護
ブック保護機能は、ブックの構造を保護できます。つまり、ユーザーがそのブック内のワークシートを追加、名前変更、削除、非表示、およびソートができます。
Infragistics Excel Engine のオブジェクト モデルから保護が強制されることはありません。これらの保護設定を履行し、対応する操作の実行をユーザーに許可または制限することは、このオブジェクト モデルを表示する UI の役割です。
保護は、protect
メソッドを呼び出すことによってブックに適用されます。
Workbook
がパスワードを使用せずに保護される場合、エンドユーザーは Excel で Workbook
の保護をパスワードを入力せずに解除できます。Workbook
の保護をコードで解除するには、unprotect
メソッドを使用できます。
Workbook
が保護される場合、この Workbook
の protection
プロパティの WorkbookProtection
インスタンスのプロパティの値は無効な操作を示します。
isProtected
が既に true の場合、protect
メソッドは無視されます。
var workbook = new Workbook();
workbook.protect(false , false );
ts
ブックが保護されているかどうかの確認この読み取り専用プロパティは、ワークブックに Protect メソッドのオーバーロードを使用して設定された保護がある場合、true を返します。
var workbook = new Workbook();
var protect = workbook.isProtected;
ts
この読み取り専用プロパティは、保護の各設定を個別に取得するためにプロパティを含む WorkbookProtection 型のオブジェクトを返します。
var workbook = new Workbook();
var protection = workbook.protection;
ts
API リファレンス