Excel에서 React Grid 붙여넣기

    Ignite UI for React IgrGrid 클립보드에 복사된 Excel 데이터를 읽을 수 있습니다. 이 섹션에서는 몇 가지 사용자 지정 코드를 사용하여 이 작업을 수행하는 방법을 보여줍니다.

    Excel에서 React 붙여넣기 예제

    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).

    상단에는 2가지 옵션이 있는 드롭다운 버튼이 있습니다.

    1. "데이터를 새 행으로 붙여넣기" – 이 모드에서는 Excel에서 복사한 모든 데이터가 그리드에 새 행으로 추가됩니다.
    2. "활성 셀부터 붙여넣기" - 이 모드에서는 그리드의 데이터를 덮어씁니다.

    붙여넣기 후의 새 데이터는 기울임꼴로 장식됩니다.

    EXAMPLE
    DATA
    TSX
    CSS

    용법

    먼저 그리드의 rendered 이벤트에 바인딩하여 텍스트 영역 요소를 만들고 관리해야 합니다.

    <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>
    tsx
    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;
        }
    ts

    이 코드는 클립보드에서 붙여넣은 데이터를 수신하는 데 사용되는 DOM textarea 요소를 만듭니다. 데이터를 텍스트 영역에 붙여넣으면 코드는 데이터를 배열로 구문 분석합니다.

    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

    그런 다음 붙여넣은 데이터를 새 레코드로 추가하거나 사용자 선택에 따라 기존 레코드를 업데이트하는 데 사용할 수 있습니다. 자세한 내용은 addRecords 및 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

    API 참조

    추가 리소스

    • Excel 내보내기- Excel 내보내기 서비스를 사용하여 그리드에서 Excel로 데이터를 내보냅니다. 또한 그리드에서 선택한 데이터만 내보낼 수 있는 옵션도 제공합니다. 내보내기 기능은 ExcelExporterService 클래스에 캡슐화되어 있으며 데이터는 MS Excel 테이블 형식으로 내보내집니다. 이 형식은 필터링, 정렬 등과 같은 기능을 허용합니다. 이렇게 하려면 ExcelExporterService의 내보내기 메서드를 호출하고 Grid 구성 요소를 첫 번째 인수로 전달해야 합니다.

    우리 커뮤니티는 활동적이며 항상 새로운 아이디어를 환영합니다.