Vue 3 component development: build a form editing system based on SpreadJS (component integration)

adopt Above We have built a project prototype based on Vue 3, and realized rapid cold start, real-time hot module update and real on-demand compilation with the help of Vite packaging free concept.

Today, we will integrate SpreadJS spreadsheet component and online table editor component to make the project prototype have the ability of Excel formula calculation, online import and export of EXCEL documents, PivotTable report and visual analysis, so as to realize the prototype of online table editing system.

            Design ideas            

  • At the same time, two components, SpreadJS and Designer (Table Editor), are created to display different component types by switching routes.

  • Add "load" and "update" buttons in the toolbar of the editor component.

  • Click "load" to load the Excel file obtained from the server, make some modifications to the component in the editor, and click "update" to transfer the modified file to the server.

  • Switch routes and display the SpreadJS component. Add "load" and "update" button s in this component. The functions are the same as above.

            Introduction to SpreadJS component            

SpreadJS   It is a native JavaScript component based on HTML5. It is compatible with more than 450 Excel formulas and provides functions highly similar to Excel. It is mainly used to develop Web Excel components and realize functional modules such as multi person collaborative editing, high-performance template design and data filling. The component architecture conforms to UMD specification and can be embedded into various applications in a native way, It is combined with the front and rear end technical framework.

(   SpreadJS (pure front-end table control)

At present, SpreadJS has made component encapsulation for Vue 2, and has not yet provided component encapsulation for Vue 3. However, we can integrate SpreadJS components and table editor into Vue 3 project by encapsulating them ourselves.

            Integrating SpreadJS with Vue3            

1. Installation module

Modify the package.json file, add the modules we need, and run the command   npm install to install all dependent projects.

```"dependencies": {    "@fortawesome/fontawesome-free": "^5.14.0",    "@grapecity/spread-excelio": "^14.0.1",    "@grapecity/spread-sheets": "^14.0.1",    "@grapecity/spread-sheets-barcode": "^14.0.1",    "@grapecity/spread-sheets-charts": "^14.0.1",    "@grapecity/spread-sheets-designer": "^14.0.1",    "@grapecity/spread-sheets-designer-resources-cn": "^14.0.1",    "@grapecity/spread-sheets-designer-vue": "^14.0.1",    "@grapecity/spread-sheets-languagepackages": "^14.0.1",    "@grapecity/spread-sheets-pdf": "^14.0.1",    "@grapecity/spread-sheets-pivot-addon": "^14.0.1",    "@grapecity/spread-sheets-print": "^14.0.1",    "@grapecity/spread-sheets-resources-zh": "^14.0.1",    "@grapecity/spread-sheets-shapes": "^14.0.1",    "@grapecity/spread-sheets-vue": "^14.0.1",    "axios": "^0.21.0",    "vue": "^3.0.2",    "vue-router": "^4.0.0-rc.5"  },```

2. Configure routing

Add 3 files under src folder.

  • router/index.js

  • views/SpreadSheet.vue

  • views/Designer.vue

Configure Routing:

```import { createRouter, createWebHistory } from "vue-router";
const routes = [  {    path: "/",    name: "Designer",    component: () => import("../views/Designer.vue"),  },  {    path: "/spreadSheet",    name: "SpreadSheet",    component: () => import("../views/SpreadSheet.vue"),  }];
export const router = createRouter({  history: createWebHistory(),  routes:routes});```

  3. Introduce in main.js:

```import { createApp } from 'vue'import { router } from './router/index'import App from './App.vue'import './index.css'
const app = createApp(App)app.use(router);app.mount('#app')```

4. Modify App.vue:

In the main.js file, add the Vue Router file to the project (in Vue 2, it was imported using Vue.use(router), but the way it was added in Vue 3 changed). As shown in the screenshot below, Vue 3 uses the createApp method to actually create the project. Before mounting the application, you need to   app.use(router)     To add to the project.

```<template><div id="app">    <div>        <router-link to="/">Designer</router-link> |        <router-link to="/spreadSheet">SpreadSheet</router-link>    </div>  <router-view/></div></template>
<script>export default {  name: 'App',  components: {  },  setup(){  }}</script>```

After seeing this, you should find that the route configuration and the way of introducing main.js in Vite are different from Vue 2. In order to better support Typescript, Vue 3 version of Vue Router requires us to import new methods to make the code work normally. The most important ones are createRouter and createWebHistory.

5. Integration designer component

After configuring the route, you can start integrating the designer component. First, add two files under the components folder:

  • components/Designer.vue

  • components /SpreadSheet.vue

Next, integrate the SpreadJS table editor in Designer.vue, and the code is shown in the following figure:

  • Add a div in the template. This div is the container of the editor. You can set the width, height and position of the container through css, that is, customize the display size and position of the editor.

  • Import dependencies required by the editor.

  • Create a new editor in the setup function.

```<template>  <div>      <div ref="ssDesigner" style="height:700px;width:100%;text-align: left;"></div>  </div></template>
import { onMounted, ref} from "vue";import "../../node_modules/@grapecity/spread-sheets/styles/gc.spread.sheets.excel2013white.css";import "../../node_modules/@grapecity/spread-sheets-designer/styles/gc.spread.sheets.designer.min.css";import "@grapecity/spread-sheets-designer-resources-cn";import "@grapecity/spread-sheets-designer";import GC from '@grapecity/spread-sheets'import ExcelIO from '@grapecity/spread-excelio'
export default {  name: 'Designer',  props: {  },  setup(props, {emit}) {    const ssDesigner = ref(null);    onMounted(() => {      var designer = new GC.Spread.Sheets.Designer.Designer(ssDesigner.value);      emit("designerInitialized", designer);    });    return {      ssDesigner    };  }}</script>```

Step 3: introduce the component and related dependencies in views/Designer.vue.

```import Designer from '../components/Designer.vue'import {ref} from "vue"import axios from "axios"import GC from '@grapecity/spread-sheets'import ExcelIO from '@grapecity/spread-excelio'```

Step 4: use the component label in the template.

```<template>  <div>    <Designer v-on:designerInitialized="designerInitialized"></Designer>  </div></template>```

Finally, initialize the editor in the setup function.

```let designer = undefined;let designerInitialized=(wb)=>{      designer = wb;      let spread = designer.getWorkbook();    }```

            How do I customize the editor toolbar?            

After completing the above steps, we have successfully integrated the SpreadJS editor into the project. Next, we will demonstrate how to create two new buttons "load" and "update" in the toolbar.

Due to SpreadJS   The online table editor adopts a new configurable design, which can be configured in json config in any area. Self customization can be achieved by modifying GC.Spread.Sheets.Designer.DefaultConfig.

1. Customize Ribbon tab

In the browser Console, enter GC.Spread.Sheets.Designer
DefaultConfig to view the default ribbon tab configuration. Refer to the default configuration, you can customize the action tab.

```let DefaultConfig = GC.Spread.Sheets.Designer.DefaultConfig;let customerRibbon = {      id: "operate",      text: "operation",      buttonGroups: [      ],};```

2. Custom button

Before defining the button, you need to define the command Commands when the button is clicked, and register the command on the commandMap attribute of config.

```let ribbonFileCommands = {        "loadTemplateCommand": {            iconClass: "ribbon-button-download",            text: "load",            //BigButton: true, commandname: "loadtemplate", execute: load}, "updatetemplate command": {iconclass: "ribbon button upload", text: "update", / / BigButton: true, commandname: "updatetemplate", execute: update}}```

The above example code registers the loadTemplateCommand and updateTemplateCommand commands.

  • execute the function corresponding to the specific execution content, that is, the load and update methods.

  • iconClass is a button style, and you can make button pictures

  • Textdisplays text for the button

  • commandName is the command name and needs to be globally unique

iconClass sample code:

```.ribbon-button-download {    background-image: url(Picture address, can be base64 svg)};```

With the command, you can add the config of the corresponding button:

```let customerRibbon = {      id: "operate",      text: "operation",      buttonGroups: [        {          label: "File operation",          thumbnailClass: "ribbon-thumbnail-spreadsettings",          commandGroup: {            children: [              {                direction: "vertical",                commands: ["loadTemplateCommand", "updateTemplateCommand"],              }            ],          },        },      ],    };```

Add custom commands and buttons to the designer's config:

```DefaultConfig.ribbon.push(customerRibbon);    DefaultConfig.commandMap = {};    Object.assign(DefaultConfig.commandMap, ribbonFileCommands);```

Finally, don't forget to supplement the code in the Load method and update method.

            Role of Load method and update method            

The Load method is used to Load excel files. After receiving the json data passed in the background, use the fromJSON method to Load the file. The code is as follows:

```let load = (e)=>{        let spread = designer.getWorkbook();        let formData = new FormData();        formData.append("fileName", "path");'spread/loadTemplate', formData, {            responseType: "json",        }).then((response) => {            if(response) {                alert("Loading succeeded");                templateJSON =;                spread.fromJSON(templateJSON);            }        }).catch((response) => {            alert("error");        })}```

The Update method is used to Update the file. When the editor operates on the loaded file, such as modifying the background color and adding text, use the toJSON method to save the current spread as json data and transfer it to the background storage. The code is as follows:

```let update = (e)=>{        let spread = designer.getWorkbook();        let spreadJSON = JSON.stringify(spread.toJSON());        let formData = new FormData();        formData.append("jsonString", spreadJSON);        formData.append("fileName", "fileName");'spread/updateTemplate', formData).then((response) => {            if(response) {                alert("Update succeeded");            }        }).catch((response) => {            alert("error");        })    }```

After completing the above operations, the new button can work normally. As shown in the following figure, click the toolbar load button, and the file has been successfully loaded in the SpreadJS table editor.

The above is Vue 3 component development: build a spreadsheet editing system based on SpreadJS (component integration). By integrating SpreadJS spreadsheet components and online editor components, the project prototype we built has the prototype of online spreadsheet editing system.

In the next chapter, we will demonstrate how to add more spreadsheet functions to the prototype of the system, and provide the whole project source code for reference.

Extended reading

Tags: Javascript html5 Vue Vue.js

Posted on Wed, 06 Oct 2021 17:24:45 -0400 by fizzwizz