Excel에서 Blazor Grid 붙여넣기

    Ignite UI for Blazor IgbGrid 클립보드에 복사된 Excel 데이터를 읽을 수 있습니다. 이 섹션에서는 사용자 지정 코드로 이를 수행하는 방법을 보여드리겠습니다.

    Blazor Paste from Excel Example

    이 샘플에서는 Excel에서 재질 UI 테이블로 IgbGrid 붙여넣기를 구현하는 방법을 보여 줍니다. 샘플로 작업하려면 Excel 스프레드시트를 열고 일부 행을 복사한 다음 키보드(Ctrl + V, Shift + Insert, Command + V)를 사용하여 그리드에 붙여넣습니다.

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

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

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

    EXAMPLE
    DATA
    MODULES
    RAZOR
    JS
    CSS

    Like this sample? Get access to our complete Ignite UI for Blazor toolkit and start building your own apps in minutes. Download it for free.

    Usage

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

    <IgbGrid  AutoGenerate="false" Data="InvoicesData" RenderedScript="WebGridPasteFromExcel" @ref="grid" Id="grid" PrimaryKey="OrderID">
        <IgbGridToolbar>
            <IgbGridToolbarActions>
                <IgbGridToolbarExporter ExportExcel="true" ExportCSV="false"> </IgbGridToolbarExporter>
            </IgbGridToolbarActions>
        </IgbGridToolbar>
    
        <IgbColumn Field="OrderID" Hidden="true"></IgbColumn>
        <IgbColumn Field="Salesperson" Header="Name" Width="200px"></IgbColumn>
        <IgbColumn Field="ShipName" Header="Ship Name" Width="200px"></IgbColumn>
        <IgbColumn Field="Country" Header="Country" Width="200px"></IgbColumn>
         <IgbColumn Field="ShipCity" Header="Ship City" Width="200px"></IgbColumn>
        <IgbColumn Field="PostalCode" Header="Postal Code" Width="200px"></IgbColumn>
    </IgbGrid>
    
    // In JavaScript
    igRegisterScript("WebGridPasteFromExcel", (evtArgs) => {
        const grid = document.getElementById("grid");
        grid.addEventListener("keydown", onWebGridPasteFromExcelKeyDown);
    }, false);
    
    function onWebGridPasteFromExcelKeyDown(eventArgs) {
        const ctrl = eventArgs.ctrlKey;
        const key = eventArgs.keyCode;
        // Ctrl-V || Shift-Ins || Cmd-V
        if ((ctrl || eventArgs.metaKey) && key === 86 || eventArgs.shiftKey && key === 45) {
            textArea.focus();
        }
    }
    
    var txtArea;
    var textArea = getTextArea();
    function getTextArea() {
        if(!txtArea) {
            const div = document.createElement("div");
            const divStyle = div.style;
            divStyle.position = "fixed";
            document.body.appendChild(div);
            txtArea = document.createElement("textarea");
            const style = txtArea.style;
            style.opacity = "0";
            style.height = "0px";
            style.width = "0px";
            style.overflow = "hidden";
            div.appendChild(txtArea);
    
            txtArea.addEventListener("paste", (eventArgs) => { onPaste(eventArgs); });
        }
        return txtArea;
    }
    
    razor

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

    function onPaste(eventArgs) {
        let data;
        const clData = "clipboardData";
    
        // get clipboard data - from window.cliboardData for IE or from the original event's arguments.
        if (window[clData]) {
            window.event.returnValue = false;
            data = window[clData].getData("text");
        } else {
            data = eventArgs[clData].getData("text/plain");
        }
    
        // process the clipboard data
        const processedData = processData(data);
            if (pasteMode === "Paste data as new records") {
                addRecords(processedData);
            } else {
                updateRecords(processedData);
            }
    }
    function processData(data) {
        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;
    }
    razor

    그런 다음 붙여넣은 데이터를 새 레코드로 추가하거나 사용자 선택에 따라 기존 레코드를 업데이트하는 데 사용할 수 있습니다. 자세한 내용은 addRecords 및 updateRecords 메서드를 참조하세요.

    function addRecords(processedData) {
        const grid = document.getElementById("grid");
        const columns = grid.visibleColumns;
        const pk = grid.primaryKey;
        const addedData = [];
        for (const curentDataRow of processedData) {
            const rowData = {};
            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, () => {
            clearStyles();
            for (const data of addedData) {
                const row = grid.getRowByKey(data[pk]);
                if (row) {
                    const rowNative = getNative(row);
                    if (rowNative) {
                        rowNative.style["font-style"] = "italic";
                        rowNative.style.color = "gray";
                    }
                }
        }
        });
    }
    
    function updateRecords(processedData) {
        const grid = document.getElementById("grid");
        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 = [];
        for (const curentDataRow of processedData) {
            const rowData = {};
            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++;
        }
    razor

    API References

    Additional Resources

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

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