React Colar de grade do Excel
O Ignite UI for React IgrGrid
pode ler dados do Excel copiados para a área de transferência. Nesta seção, mostraremos como fazer isso com algum código personalizado.
React Paste from Excel Example
This sample demonstrates how to implement pasting from Excel into the IgrGrid
Material UI table.
To work with the sample open up any Excel spreadsheet, copy some rows, and paste it into the grid using the keyboard (CTRL + V, SHIFT + INSERT,CMD + V).
Na parte superior, há um botão suspenso com 2 opções:
- "Colar dados como novas linhas" – neste modo, todos os dados copiados do Excel serão anexados à grade como novas linhas
- "Colar a partir da célula ativa" – neste modo, os dados na grade serão substituídos.
Os novos dados após a colagem são decorados em itálico.
Usage
Primeiro, você deve associar ao evento da rendered
grade para criar e gerenciar um elemento de área de texto:
<IgrGrid autoGenerate={false} data={this.invoicesData} onRendered={this.webGridPasteFromExcel} ref={this.gridRef} id="grid" primaryKey="OrderID">
<IgrGridToolbar>
<IgrGridToolbarActions>
<IgrGridToolbarExporter exportExcel={true} exportCSV={false}>
</IgrGridToolbarExporter>
</IgrGridToolbarActions>
</IgrGridToolbar>
<IgrColumn field="OrderID" hidden={true}></IgrColumn>
<IgrColumn field="Salesperson" header="Name" width="200px"></IgrColumn>
<IgrColumn field="ShipName" header="Ship Name" width="200px"></IgrColumn>
<IgrColumn field="Country" header="Country" width="200px"></IgrColumn>
<IgrColumn field="ShipCity" header="Ship City" width="200px"></IgrColumn>
<IgrColumn field="PostalCode" header="Postal Code" width="200px"> </IgrColumn>
</IgrGrid>
public webGridPasteFromExcel(e: CustomEvent<any>) {
const grid = e.target as IgrGrid;
this.onKeyDown = this.onKeyDown.bind(this);
grid.addEventListener("keydown", this.onKeyDown);
}
public onKeyDown(eventArgs: any): void {
const ctrl = eventArgs.ctrlKey;
const key = eventArgs.keyCode;
// Ctrl-V || Shift-Ins || Cmd-V
if ((ctrl || eventArgs.metaKey) && key === 86 || eventArgs.shiftKey && key === 45) {
this.textArea.focus();
}
}
private txtArea: any;
public get textArea() {
if(!this.txtArea) {
const div = document.createElement("div");
const divStyle = div.style;
divStyle.position = "fixed";
document.body.appendChild(div);
this.txtArea = document.createElement("textarea");
const style = this.txtArea.style;
style.opacity = "0";
style.height = "0px";
style.width = "0px";
style.overflow = "hidden";
div.appendChild(this.txtArea);
this.txtArea.addEventListener("paste", (eventArgs: any) => { this.onPaste(eventArgs); });
}
return this.txtArea;
}
O código cria um elemento textarea DOM que é usado para receber os dados colados da área de transferência. Quando os dados são colados na área de texto, o código os analisa em uma matriz.
public onPaste(eventArgs: any) {
let data;
const clData: any = "clipboardData";
// get clipboard data - from window.cliboardData for IE or from the original event's arguments.
if (window[clData] as any) {
(window.event as any).returnValue = false;
data = (window[clData] as any).getData("text");
} else {
data = eventArgs[clData].getData("text/plain");
}
// process the clipboard data
const processedData = this.processData(data);
if (this.pasteMode === "Paste data as new records") {
this.addRecords(processedData);
} else {
this.updateRecords(processedData);
}
}
public processData(data: any) {
const pasteData = data.split("\n");
for (let i = 0; i < pasteData.length; i++) {
pasteData[i] = pasteData[i].split("\t");
// Check if last row is a dummy row
if (pasteData[pasteData.length - 1].length === 1 && pasteData[pasteData.length - 1][0] === "") {
pasteData.pop();
}
// remove empty data
if (pasteData.length === 1 &&
pasteData[0].length === 1 &&
(pasteData[0][0] === "" || pasteData[0][0] === "\r")) {
pasteData.pop();
}
}
return pasteData;
}
Os dados colados podem ser adicionados como novos registros ou usados para atualizar os registros existentes com base na seleção do usuário. Para referência, consulte os métodos addRecords e updateRecords.
public addRecords(processedData: any[]) {
const grid = this.grid as any;
const columns = grid.visibleColumns;
const pk = grid.primaryKey;
const addedData: any[] = [];
for (const curentDataRow of processedData) {
const rowData = {} as any;
for (const col of columns) {
const index = columns.indexOf(col);
rowData[col.field] = curentDataRow[index];
}
// generate PK
rowData[pk] = grid.data.length + 1;
grid.addRow(rowData);
addedData.push(rowData);
}
// scroll to last added row
grid.navigateTo(grid.data.length - 1, 0, () => {
this.clearStyles();
for (const data of addedData) {
const row = grid.getRowByKey(data[pk]);
if (row) {
const rowNative = this.getNative(row) as any;
if (rowNative) {
rowNative.style["font-style"] = "italic";
rowNative.style.color = "gray";
}
}
}
});
}
public updateRecords(processedData: any[]) {
const grid = this.grid as any;
const cell = grid.selectedCells[0];
const pk = grid.primaryKey;
if (!cell) { return; }
const rowIndex = cell.row.index;
const columns = grid.visibleColumns;
const cellIndex = grid.visibleColumns.indexOf(cell.column);
let index = 0;
const updatedRecsPK: any[] = [];
for (const curentDataRow of processedData) {
const rowData = {} as any;
const dataRec = grid.data[rowIndex + index];
const rowPkValue = dataRec ? dataRec[pk] : grid.data.length + 1;
rowData[pk] = rowPkValue;
for (let j = 0; j < columns.length; j++) {
let currentCell;
if (j >= cellIndex) {
currentCell = curentDataRow.shift();
}
const colKey = columns[j].field;
rowData[colKey] = currentCell || (dataRec ? dataRec[colKey] : null);
}
if (!dataRec) {
// no rec to update, add instead
rowData[pk] = rowPkValue;
grid.addRow(rowData);
continue;
}
grid.updateRow(rowData, rowPkValue);
updatedRecsPK.push(rowPkValue);
index++;
}
this.clearStyles();
for (const pkVal of updatedRecsPK) {
const row = grid.getRowByKey(pkVal);
if (row) {
const rowNative = this.getNative(row) as any;
if (rowNative) {
rowNative.style["font-style"] = "italic";
rowNative.style.color = "gray";
}
}
}
}
API References
Additional Resources
- Exportador do Excel- Use o serviço Exportador do Excel para exportar dados do Excel do Grid. Ele também oferece a opção de exportar apenas os dados selecionados da Grade. A funcionalidade de exportação é encapsulada na classe ExcelExporterService e os dados são exportados no formato de tabela do MS Excel. Este formato permite recursos como filtragem, classificação, etc. Para fazer isso, você precisa invocar o método de exportação do ExcelExporterService e passar o componente Grid como primeiro argumento.
Nossa comunidade é ativa e sempre acolhedora para novas ideias.