Close
Angular React Web Components Blazor Blazor
Premium

Blazor Grid Excel から貼り付け

Ignite UI for Blazor IgbGrid は、クリップボードにコピーした Excel データを読み込むことができます。このトピックでは、カスタムコードを使用して実装する方法について説明します。

Blazor Excel から貼り付けの例

このサンプルでは、Excel から IgbGrid の貼り付けを実装する方法を紹介します。 サンプルは、Excel スプレッドシートを開いて行をコピーし、キーボード (CTRL + VSHIFT + INSERTCMD + V) を使用してグリッドに貼り付けます。

上部に2 つのオプションとドロップダウン ボタンがあります。

  1. 新規行としてデータを貼り付け - このモードでは、Excel からコピーしたデータが新規行としてグリッドに追加されます。
  2. アクティブ セルから開始する貼り付け - このモードではグリッド データが上書きされます。

貼り付け後の新しいデータはイタリックで装飾されます。

使用方法

最初にグリッドの 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;
}

このコードはクリップボードから貼り付けられたデータを受け取るための DOM textarea 要素を作成します。コードは 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;
}

貼り付けたデータは、新しいレコードとして追加したり、ユーザーの選択に基づいて既存のレコードを更新するために使用したりすることができます。 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++;
    }

API リファレンス

IgbGrid

その他のリソース

  • Excel エクスポーター - Excel エクスポーター サービスを使用して、グリッドから Excel にデータをエクスポートします。選択したデータのみをグリッドからエクスポートするオプションもあります。エクスポート機能は、ExcelExporterService クラスでカプセル化され、MS Excel テーブル形式でデータをエクスポートします。この形式はフィルタリングやソートなどの機能が使用でき、ExcelExporterService の export メソッドを呼び出して最初の引数として グリッド コンポーネントを渡します。

コミュニティに参加して新しいアイデアをご提案ください。