come creare un editor collaborativo di Excel con GridJs

Guida all’editor collaborativo di Excel

Panoramica dell’architettura

Il diagramma seguente mostra come GridJs consente la modifica collaborativa con più utenti, un backend Spring Boot, comunicazione WebSocket e un database MySQL per la gestione dello stato.

Architettura collaborativa di GridJs

Prerequisiti

Prima di iniziare, assicurati di aver installato quanto segue:

  • Java 8+
  • Maven
  • MySQL (o un altro database SQL supportato)
  • (Opzionale) Docker se preferisci eseguirlo in contenitori
  • Una licenza Aspose.Cells valida (o licenza temporanea)

Step 1: Clone the Demo Project

Clone the official Aspose.Cells GridJs demo repository:

git clone https://github.com/aspose-cells/Aspose.Cells.Grid-for-Java.git
cd Aspose.Cells-for-Java/Examples.GridJs.Collaborative

Step 2: Configure Collaborative Mode

Open the src/main/resources/application.properties file and adjust the settings:

# Directory containing spreadsheet files
testconfig.ListDir=/app/wb

# Directory for storing cache files
testconfig.CachePath=/app/grid_cache

# Aspose.Cells license file
testconfig.AsposeLicensePath=/app/license

# Enable collaborative mode
gridjs.iscollabrative=true

# Database connection (example: MySQL)
spring.datasource.url=jdbc:mysql://localhost:3306/gridjsdemodb?createDatabaseIfNotExist=true&useUnicode=true&serverTimezone=UTC&useSSL=false
spring.datasource.username=root
spring.datasource.password=root
spring.sql.init.platform=mysql

Questo permette a più utenti di modificare contemporaneamente lo stesso foglio di calcolo.
Le modifiche vengono archiviate nel database e sincronizzate tra i client in tempo reale.


Step 3: Run the Application

Run with Maven:

mvn spring-boot:run

Oppure direttamente dalla classe principale:

src/main/java/com/aspose/gridjsdemo/usermanagement/UserManagementApplication.java

Step 4: Test Collaborative Editing

Open your browser and navigate to:
👉 http://localhost:8080/gridjsdemo/list

Steps:

  1. A login page appears. Click Create User to register User1 and log in. You will then see the file list.
  2. Open a file from the list. The spreadsheet editor will load.
  3. Copy the same URL into another browser window. It will redirect to the login page. Create User2 and log in.
  4. Both users now see the same spreadsheet.
  5. If User1 edits the spreadsheet, User2 will see the changes in real time.
  6. If User2 edits, User1 will see the changes as well.
  7. Users can also download and save the file.

Passaggio 5: Eseguire in Docker (Opzionale)

Se si esegue in Docker, modificare la riga 10 di docker-compose.yml per mappare il file di licenza.

Ad esempio, se il file di licenza è in C:/license/aspose.lic:

volumes:
  - C:/license/aspose.lic:/app/license  # optional: set Aspose license file

Questo mappa il file locale nel contenitore.

Poi compilare ed eseguire:

docker-compose up --build

Accedi all’app a:
👉 http://localhost:8080/gridjsdemo/list


Key Configuration Details

1. Enable Collaborative Mode

In /src/main/resources/application.properties:

gridjs.iscollabrative=true

Nella configurazione lato server /src/main/java/com/aspose/gridjsdemo/filemanagement/FileConfig.java:

@Bean
public GridJsOptions gridJsOptions() {
    //..... other options
    //here we shall set true for collaborative mode
    options.setCollaborative(true);
    return options;
}

Oppure globalmente:

Config.setCollaborative(true);

Nelle opzioni di caricamento lato client /src/main/resources/templates/file/index.html:

const option = {
    //..... other options
    //here we shall set true for collaborative mode
    isCollaborative: true
    //..... other options
};

2. User System Integration

The demo uses Spring Security for a simple user system.

You must provide a CoWorkUserProvider implementation to connect GridJs with your user system:

In server-side config /src/main/java/com/aspose/gridjsdemo/filemanagement/FileConfig.java:

For example: here we defined MyCustomUser to implement all the interfaces in CoWorkUserProvider.

@Bean
public CoWorkUserProvider currentUserProvider() {
    return new MyCustomUser();
}

In /src/main/java/com/aspose/gridjsdemo/filemanagement/MyCustomUser.java:

public class MyCustomUser implements CoWorkUserProvider {
    //Get the current login user name
    @Override
    public String getCurrentUserName() {
        return getCurrentUser().getUsername();
    }

    //Get the current login user Id
    @Override
    public Long getCurrentUserId() {
        return getCurrentUser().getUserId();
    }

    //Get the current login user permission
    @Override
    public CoWorkUserPermission getPermission() {
        return CoWorkUserPermission.EDITABLE;
    }

    private static CustomUserDetails getCurrentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.getPrincipal() instanceof CustomUserDetails) {
            return (CustomUserDetails) authentication.getPrincipal();
        }
        throw new IllegalStateException("User not authenticated");
    }
}

3. WebSocket Configuration

The demo uses Spring WebSocket with STOMP.

Example config:

In /src/main/java/com/aspose/gridjsdemo/messages/WebSocketConfig.java:

public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/topic");
        config.setApplicationDestinationPrefixes("/app");
        config.setUserDestinationPrefix("/user");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/ws")
                .setAllowedOrigins("http://localhost:8080")
                .withSockJS();
    }
}

GridJs si aspetta che messageTopic corrisponda a “/topic/opr” che è il valore di default:

com.aspose.gridjs.Config.setMessageTopic("/topic/opr");

O:

@Bean
    public GridJsOptions gridJsOptions() {
	//.... other options
    	options.setMessageTopic("/topic/opr");
    	//.... other options
        return options;
    }

Sul lato client:

xs.setCollaborativeSetting('/GridJs2/msg','/ws','/app/opr','/user/queue','/topic/opr');

Qui, /GridJs2/msg corrisponde al percorso definito in
src/main/java/com/aspose/gridjsdemo/filemanagement/controller/GridJsOprController.java:

@RequestMapping("/GridJs2/msg")

Esempio con percorsi WebSocket personalizzati

Se il server utilizza una configurazione diversa:

public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/topic_gridjs");
        config.setApplicationDestinationPrefixes("/app_gridjs");
        config.setUserDestinationPrefix("/user_gridjs");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/ws_gridjs")
                .setAllowedOrigins("http://localhost:8080")
                .withSockJS();
    }
}

Allora è necessario impostare:

Lato server:

com.aspose.gridjs.Config.setMessageTopic("/topic_gridjs/opr");

o

    @Bean
    public GridJsOptions gridJsOptions() {
	//.... other option
    	options.setMessageTopic("/topic_gridjs/opr");
    	//.... other option
        return options;
    }

Lato client:

xs.setCollaborativeSetting('/GridJs2/msg','/ws_gridjs','/app_gridjs/opr','/user_gridjs/queue','/topic_gridjs/opr');

il documento di dettaglio per setCollaborativeSetting può essere trovato qui

⚠️ Nota: Per impostazione predefinita, la configurazione demo funziona subito.
La configurazione extra è richiesta solo se la tua app personalizza gli endpoint WebSocket.

Ricorda anche: la modalità collaborativa non supporta il caricamento pigro.
Non abilitare Config.setLazyLoading(true).


Additional Notes

  • We can add file uploads to load and edit spreadsheet file from upload directory.
  • Integrate with cloud storage like AWS S3 or Azure Blob.

Conclusione

Con Aspose.Cells.GridJs, puoi costruire rapidamente un potente editor Excel collaborativo.
La combinazione di backend Java, frontend GridJs, archiviazione SQL e messaggistica WebSocket garantisce un editing di fogli di calcolo in tempo reale affidabile.


Resources