React Adaptador de gráfico de hoja de cálculo
El componente React Hoja de cálculo permite mostrar gráficos en su IgrSpreadsheet
.
React Ejemplo de adaptador de gráfico de hoja de cálculo
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 { ExcelUtility } from './ExcelUtility' ;
import { IgrExcelXlsxModule } from "@infragistics/igniteui-react-excel" ;
import { IgrExcelCoreModule } from "@infragistics/igniteui-react-excel" ;
import { IgrExcelModule } from "@infragistics/igniteui-react-excel" ;
import { IgrSpreadsheetModule } from "@infragistics/igniteui-react-spreadsheet" ;
import { IgrSpreadsheet } from "@infragistics/igniteui-react-spreadsheet" ;
import { IgrSpreadsheetChartAdapterModule } from "@infragistics/igniteui-react-spreadsheet-chart-adapter" ;
import { SpreadsheetChartAdapter } from "@infragistics/igniteui-react-spreadsheet-chart-adapter" ;
import { Worksheet } from "@infragistics/igniteui-react-excel" ;
import { WorksheetCell } from "@infragistics/igniteui-react-excel" ;
import { ChartType, ChartTitle, FormattedString } from "@infragistics/igniteui-react-excel" ;
IgrExcelCoreModule.register();
IgrExcelModule.register();
IgrExcelXlsxModule.register();
IgrSpreadsheetModule.register();
IgrSpreadsheetChartAdapterModule.register();
export default class SpreadsheetAdapterForCharts extends React.Component {
public spreadsheet: IgrSpreadsheet;
constructor (props: any ) {
super (props);
this .onSpreadsheetRef = this .onSpreadsheetRef.bind(this );
}
public render (): JSX .Element {
return (
<div className ="container sample" >
<IgrSpreadsheet ref ={this.onSpreadsheetRef} height ="calc(100% - 25px)" width ="100%" />
</div >
);
}
public onSpreadsheetRef(spreadsheet: IgrSpreadsheet) {
if (spreadsheet) {
this .spreadsheet = spreadsheet;
this .spreadsheet.chartAdapter = new SpreadsheetChartAdapter();
const url = "https://static.infragistics.com/xplatform/excel/ChartData.xlsx" ;
ExcelUtility.loadFromUrl(url).then((w) => {
this .spreadsheet.workbook = w;
const sheet : Worksheet = this .spreadsheet.workbook.worksheets(0 );
sheet.defaultColumnWidth = 450 * 20 ;
sheet.rows(0 ).height = 150 * 20 ;
const cell1 : WorksheetCell = sheet.getCell("A1" );
const cell2 : WorksheetCell = sheet.getCell("B1" );
const cell3 : WorksheetCell = sheet.getCell("C1" );
const cell4 : WorksheetCell = sheet.getCell("D1" );
const dataCellAddress = "A3:D6" ;
const title : ChartTitle = new ChartTitle();
title.text = new FormattedString("Line Chart" );
const chart1 = sheet.shapes().addChart(ChartType.Line, cell1, { x: 5 , y: 5 }, cell1, { x: 90 , y: 90 });
chart1.chartTitle = title;
chart1.setSourceData(dataCellAddress, true );
const title2 : ChartTitle = new ChartTitle();
title2.text = new FormattedString("Column Chart" );
const chart2 = sheet.shapes().addChart(ChartType.ColumnClustered, cell2, { x: 5 , y: 5 }, cell2, { x: 90 , y: 90 });
chart2.chartTitle = title2;
chart2.setSourceData(dataCellAddress, true );
const title3 : ChartTitle = new ChartTitle();
title3.text = new FormattedString("Area Chart" );
const chart3 = sheet.shapes().addChart(ChartType.Area, cell3, { x: 5 , y: 5 }, cell3, { x: 90 , y: 90 });
chart3.chartTitle = title3;
chart3.setSourceData(dataCellAddress, true );
const title4 : ChartTitle = new ChartTitle();
title4.text = new FormattedString("Pie Chart" );
const chart4 = sheet.shapes().addChart(ChartType.Pie, cell4, { x: 5 , y: 5 }, cell4, { x: 90 , y: 90 });
chart4.chartTitle = title4;
chart4.setSourceData(dataCellAddress, true );
});
}
}
}
const root = ReactDOM.createRoot (document.getElementById('root' ));
root.render (<SpreadsheetAdapterForCharts /> );
tsx コピー
¿Te gusta este ejemplo? Obtén acceso a nuestro kit de herramientas completo Ignite UI for React y comienza a crear tus propias aplicaciones en minutos. Descárgalo gratis.
Descripción general del adaptador de gráficos
Con chartAdapter
puede mostrar los gráficos en la hoja de cálculo. Los adaptadores de gráficos de hoja de cálculo crean e inicializan elementos de gráfico para la hoja de cálculo basándose en una instancia de Infragistics.Documents.Excel.WorksheetChart.
Para agregar un WorksheetChart a una hoja de trabajo, debe usar el método addChart
de la colección Shapes de la hoja de trabajo. Puede encontrar más detalles sobre cómo agregar gráficos en Excel a continuación.
Aquí está la descripción paso a paso:
Agregue la referencia SpreadsheetChartAdapterModule a su proyecto
Cree una instancia de una clase SpreadsheetChartAdapter asignándola a la hoja de cálculo
Ejecute su aplicación y cargue una hoja de trabajo que contenga un gráfico.
Tipos de gráficos admitidos
Hay más de 35 tipos de gráficos admitidos por los ChartAdapters de hoja de cálculo, incluidos Línea, Área, Columna y Anillo. Vea la lista completa aquí:
Gráficos de columnas
Columna agrupada
columna apilada
Columna 100% apilada
Gráficos de líneas
Línea
Línea con marcadores
línea apilada
Línea apilada con marcadores
Línea 100% apilada
Línea 100% apilada con marcadores.
Gráficos circulares
Gráficos de anillos
Gráfica de barras
barra agrupada
barra apilada
barra 100% apilada
Gráficos de área
Área
Área apilada
Área 100% apilada
Gráficos XY (dispersión) y de burbujas
Dispersión (solo con marcador)
Dispersar con líneas suaves
Dispersión con líneas suaves y marcadores.
Dispersión con líneas rectas
Dispersión con líneas rectas y marcadores.
Burbuja (sin efectos)
Efecto Burbuja3DE
Gráficos de acciones
Cierre alto-bajo
Abrir-alto-bajo-cerrar
Volumen-alto-bajo-cierre
Volumen-apertura-alto-bajo-cierre
Gráficos de radar
Radar sin marcadores
Radar con marcadores
Radar lleno
Gráficos combinados
Gráfico de columnas y líneas que comparten xAxis
Gráfico de columnas y líneas y segundo eje x
Área y columna apiladas
Combinación personalizada
dependencias
En el siguiente fragmento de código, se utiliza una clase ExcelUtility externa para guardar y cargar un libro.
Al configurar su control de hoja de cálculo React para agregar gráficos, deberá importar la clase de la SpreadsheetChartAdapter
siguiente manera:
import { IgrExcelXlsxModule } from 'igniteui-react-excel' ;
import { IgrExcelCoreModule } from 'igniteui-react-excel' ;
import { IgrExcelModule } from 'igniteui-react-excel' ;
import { IgrSpreadsheetChartAdapterModule } from 'igniteui-react-spreadsheet-chart-adapter' ;
import { SpreadsheetChartAdapter } from 'igniteui-react-spreadsheet-chart-adapter' ;
import { ExcelUtility } from "ExcelUtility" ;
import { Worksheet } from 'igniteui-react-excel' ;
import { WorksheetCell } from 'igniteui-react-excel' ;
import { ChartType, ChartTitle, FormattedString, Workbook } from 'igniteui-react-excel' ;
IgrExcelCoreModule.register();
IgrExcelModule.register();
IgrExcelXlsxModule.register();
IgrSpreadsheetModule.register();
IgrSpreadsheetChartAdapterModule.register();
ts
Fragmento de código
En el siguiente fragmento de código se muestra cómo agregar gráficos a la hoja de cálculo que se está viendo actualmente en el IgrSpreadsheet
control:
this .spreadsheet.chartAdapter = new SpreadsheetChartAdapter();
ExcelUtility.loadFromUrl(process.env.PUBLIC_URL + "/ExcelFiles/ChartData.xlsx" ).then((w ) => {
this .spreadsheet.workbook = w;
const sheet: Worksheet = this .spreadsheet.workbook.worksheets(0 );
sheet.defaultColumnWidth = 500 * 20 ;
sheet.rows(0 ).height = 150 * 20 ;
const cell1: WorksheetCell = sheet.getCell("A1" );
const cell2: WorksheetCell = sheet.getCell("B1" );
const cell3: WorksheetCell = sheet.getCell("C1" );
const cell4: WorksheetCell = sheet.getCell("D1" );
const dataCellAddress = "A4:D6" ;
const chart1 = sheet.shapes().addChart(ChartType.Line, cell1, { x : 0 , y : 0 }, cell1, { x : 100 , y : 100 });
const title: React ChartTitle = new ChartTitle();
title.text = new FormattedString("Line Chart" );
chart1.chartTitle = title;
chart1.setSourceData(dataCellAddress, true );
const chart2 = sheet.shapes().addChart(ChartType.ColumnClustered, cell2, { x : 0 , y : 0 }, cell2, { x : 100 , y : 100 });
const title2: ChartTitle = new ChartTitle();
title2.text = new FormattedString("Column Chart" );
chart2.chartTitle = title2;
chart2.setSourceData(dataCellAddress, true );
const chart3 = sheet.shapes().addChart(ChartType.Area, cell3, { x : 0 , y : 0 }, cell3, { x : 100 , y : 100 });
const title3: ChartTitle = new ChartTitle();
title3.text = new FormattedString("Area Chart" );
chart3.chartTitle = title3;
chart3.setSourceData(dataCellAddress, true );
const chart4 = sheet.shapes().addChart(ChartType.Pie, cell4, { x : 0 , y : 0 }, cell4, { x : 100 , y : 100 });
const title4: ChartTitle = new ChartTitle();
title4.text = new FormattedString("Pie Chart" );
chart4.chartTitle = title4;
chart4.setSourceData(dataCellAddress, true );
});
typescript
Referencias de API