Web Components Pegar cuadrícula de Excel

    El Ignite UI for Web Components IgcGridComponent puede leer los datos de Excel que se copian en el portapapeles. En esta sección te mostraremos cómo hacer esto con algún código personalizado.

    Web Components Pegar desde Excel Ejemplo

    En este ejemplo se muestra cómo implementar el pegado desde Excel en la tabla de la interfaz de usuario de IgcGridComponent material. Para trabajar con el ejemplo, abra cualquier hoja de cálculo de Excel, copie algunas filas y péguelas en la cuadrícula con el teclado (Ctrl + V, Shift + Insert, Command + V).

    En la parte superior hay un botón desplegable con 2 opciones:

    1. "Pegar datos como filas nuevas": en este modo, cualquier dato copiado de Excel se agregará a la cuadrícula como filas nuevas.
    2. "Pegar desde la celda activa": en este modo se sobrescribirán los datos de la cuadrícula.

    Los nuevos datos después del pegado están decorados en cursiva.

    EXAMPLE
    DATA
    TS
    HTML
    CSS

    ¿Te gusta esta muestra? Obtenga acceso a nuestro kit de herramientas de Ignite UI for Web Components completo y comience a crear sus propias aplicaciones en minutos. Descárgalo gratis.

    Uso

    Primero debe enlazar al evento de la cuadrícula para crear y administrar un elemento de área de rendered texto:

    <igc-grid auto-generate="false" name="grid" id="grid" primary-key="OrderID">
        <igc-grid-toolbar>
            <igc-grid-toolbar-actions >
                <igc-grid-toolbar-exporter export-excel="true" export-csv="false"> </igc-grid-toolbar-exporter>
            </igc-grid-toolbar-actions>
        </igc-grid-toolbar>
        <igc-column field="OrderID" hidden="true"></igc-column>
        <igc-column field="Salesperson" header="Name" width="200px"></igc-column>
        <igc-column field="ShipName" header="Ship Name" width="200px"></igc-column>
        <igc-column field="Country" header="Country" width="200px"></igc-column>
        <igc-column field="ShipCity" header="Ship City" width="200px"></igc-column>
        <igc-column field="PostalCode" header="Postal Code" width="200px"> </igc-column>
    </igc-grid>
    html
    public webGridPasteFromExcel() {
        const grid = document.getElementById("grid") as any;
        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;
        }
    ts

    El código crea un elemento de área de texto DOM que se utiliza para recibir los datos pegados del portapapeles. Cuando los datos se pegan en el área de texto, el código los analiza en una 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;
    }
    ts

    Los datos pegados se pueden agregar como nuevos registros o se pueden usar para actualizar los registros existentes en función de la selección del usuario. Como referencia, consulte los métodos addRecords y 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";
                }
            }
        }
    }
    ts
    Ignite UI for Web Components | CTA Banner

    Referencias de API

    Recursos adicionales

    • Exportador de Excel: use el servicio Exportador de Excel para exportar datos a Excel desde la cuadrícula. También ofrece la opción de exportar solo los datos seleccionados de la cuadrícula. La funcionalidad de exportación se encapsula en la clase ExcelExporterService y los datos se exportan en formato de tabla de MS Excel. Este formato permite funciones como filtrado, clasificación, etc. Para ello, debe invocar el método de exportación de ExcelExporterService y pasar el componente Grid como primer argumento.

    Nuestra comunidad es activa y siempre da la bienvenida a nuevas ideas.