40行代碼實現spreadjs在線excel表格多人實時編輯

思路

表格的編輯,即用戶對錶格的操做,操做表格改變了表格的內容。從代碼層面來說,用戶的操做最終都轉化成了一個個command,js執行這些command改變了表格內容。由於多個用戶的操做就是一個個command的合集,spreadjs提供了anyscLicenser事件來監聽用戶的操做獲取command,用戶經過websocket推送拿到別的用戶的操做command,執行這些command,那麼內容就同步了。web

核心代碼

所以核心代碼以下,可下載文件下來查看效果websocket

var spread = new GC.Spread.Sheets.Workbook(document.getElementById("ss"));
        var spread1 = new GC.Spread.Sheets.Workbook(document.getElementById("ss1"));
        var sheet = spread.getActiveSheet();
        var sheet1 = spread1.getActiveSheet();
        var spreadNS = GC.Spread.Sheets;
        var command = {
            canUndo: true,
            execute: function (context, options, isUndo) {
                var Commands = GC.Spread.Sheets.Commands;
                if (isUndo) {
                    Commands.undoTransaction(context, options);
                    return true;
                } else {
                    Commands.startTransaction(context, options);
                    var sheet = context.getSheetFromName(options.sheetName);
                    var cell = sheet.getCell(options.row, options.col);
                    cell.backColor(options.backColor);
                    Commands.endTransaction(context, options);
                    return true;
                }
            }
        };
        var commandManager = spread.commandManager();
        var commandManager1 = spread1.commandManager();
        commandManager.register("changeBackColor", command);
        commandManager1.register("changeBackColor", command);

        /*添加監聽*/
        spread.commandManager().addListener("anyscLicenser",function(){
            for(var i=0;i<arguments.length;i++){
                var cmd = arguments[i].command;
                console.log(cmd)
                if(cmd.clipboardText){
                    cmd.fromSheet = null;
                    cmd.fromRanges = null;
                }
                commandManager1.execute(cmd)
            }
        });
相關文章
相關標籤/搜索