Detailed explanation of Excel parsing and exporting based on Vue

Detailed explanation of Excel parsing and exporting based on Vue

Preface

Recently, I was sorting out the business requirements involved in daily development, and I happened to think of the parsing and uploading of Excel, which is quite common in development. Let's take advantage of the weekend to sort it out and learn it.

Basic Introduction

Mainly based on Vue+element to implement file parsing and export, the plug-in used is xlsx, the specific methods in it, if you are interested, go and study it. The basic style and configuration will not be repeated, and it is relatively simple. Let's go straight to the staple food

Code Implementation

Basic structure

The user clicks on the file upload, and the Excel table is displayed in the JSON format on the page. The user performs operations, checks the data, and submits it to the service. The upload operation uses the upload component in the element

   <!-- Upload file button -->
   <div class="buttonBox">
     <el-upload
       action
       accept=".xlsx, .xls"
       :auto-upload="false"
       :show-file-list="false"
       :on-change="handle"
     >
       <el-button type="primary" slot="trigger">Select EXCEL file</el-button>
     </el-upload>

     <el-button type="success" @click="submit" :disabled="disable">Collect data and submit</el-button>
   </div>

   <!-- Parsed data-->
   <div class="tableBox" v-show="show">
     <h3>
       <i class="el-icon-info"></i>
       My dear, the following is the data that has been collected. After checking that it is correct, please click the "Submit Collected Data" button to upload it to the server!
     </h3>

     <el-table :data="tempData" style="width: 100%" :height="height" border>
       <el-table-column prop="name" label="Name" min-width="50%"></el-table-column>
       <el-table-column prop="phone" label="电话" min-width="50%"></el-table-column>
     </el-table>
   </div>

Upload analysis

The uploaded file stream can be obtained through the upload component (see the figure below)

Convert the file stream to binary. Here we can add the corresponding method in the utils file (as follows)

// Read the file in binary format export function readFile(file) {
    return new Promise(resolve => {
        let reader = new FileReader();
        reader.readAsBinaryString(file);
        reader.onload = ev => {
             resolve(ev.target.result);
        };
    });
 }

Convert binary to json through xlsx so that it can be displayed

  //Read the data in FILE (convert to JSON format)
  let data = await readFile(file);
  let workbook = xlsx.read(data, { type: "binary" }),
    worksheet = workbook.Sheets[workbook.SheetNames[0]];
  data = xlsx.utils.sheet_to_json(worksheet);
  // Print the results and add the following figure console.log(workbook);

To convert the read data into data that can be passed to the server, we need to encapsulate a mapping table to correspond to the format passed to the backend (as shown below)

// Field correspondence table export let character = {
        name: {
            text: "Name",
            type: 'string'
        },
        phone:
            text: "Phone",
            type: 'string'
        }
    };

Convert data formats

   let arr = [];
    data.forEach(item => {
        let obj = {};
        for (let key in character) {
          if (!character.hasOwnProperty(key)) break;
          let v = character[key],
            text = v.text,
            type = v.type;
          v = item[text] || "";
          type === "string" ? (v = String(v)) : null;
          type === "number" ? (v = Number(v)) : null;
          obj[key] = v;
        }
      arr.push(obj);
    });

Send to server

Here we need to see if the server supports sending multiple files together. If it does not support it, our front end can use recursive sending method to send them one by one. You can communicate with the back end for specific circumstances. We use recursive transmission here.

    //Submit data to the server async submit() {
      if (this.tempData.length <= 0) {
        this.$message({
          message: "My dear, please select the EXCEL file first!",
          type: "warning",
          showClose: true
        });
        return;
      }

      this.disable = true;
      let loadingInstance = Loading.service({
        text: "My dear, please wait for a moment. I am working very hard to deal with it!",
        background: "rgba(0,0,0,.5)"
      });

      // What to do after completion let complate = () => {
        this.$message({
          message: "My dear, I have uploaded the data for you!",
          type: "success",
          showClose: true
        });
        this.show = false;
        this.disable = false;
        loadingInstance.close();
      };

      // Need to pass data to the server one by one let n = 0;
      let send = async () => {
        if (n > this.tempData.length - 1) {
          // All passed complate();
          return;
        }
        let body = this.tempData[n];
        // Go through the interface let result = await createAPI(body);
        if (parseInt(result.code) === 0) {
          // Success n++;
        }
        send();
      };
      send();
    }

The above is a summary of the analysis and uploading of Excel files. In fact, it is not very difficult. These are the businesses that are often involved in daily development. Next, let’s take a look at Excel export.

Excel export

Basic structure

As soon as you enter the page, get the file you just uploaded, then display it in a table, and then make a page... I won't talk about these, let's start directly by clicking the Export Excel button and look at the page structure first

  <div class="container">
    <!-- Upload button -->
    <div class="buttonBox">
      <router-link to="/upload">
        <el-tooltip content="EXCEL data collection" placement="top">
          <el-button type="primary" icon="el-icon-edit" circle></el-button>
        </el-tooltip>
      </router-link>
    </div>

    <!-- Search Area -->
    <div class="searchBox">
      <el-input v-model="search" placeholder="Fuzzy search based on name and mobile phone" @change="searchHandle"></el-input>
      <el-button type="success" @click="submit" :disabled="disabled">Export selected data</el-button>
    </div>

    <!-- List area -->
    <div class="tableBox">
      <el-table
        :data="tableData"
        :height="height"
        style="width: 100%"
        v-loading="loading"
        element-loading-text="My lady, I am working hard to load..."
        @selection-change="selectionChange"
      >
        <el-table-column type="selection" width="50" align="center"></el-table-column>
        <el-table-column prop="id" label="Number" min-width="10%"></el-table-column>
        <el-table-column prop="name" label="Name" min-width="20%"></el-table-column>
        <el-table-column prop="phone" label="电话" min-width="20%"></el-table-column>
        <el-table-column prop="time" label="Creation time" min-width="25%" :formatter="formatter"></el-table-column>
      </el-table>
    </div>

    <!-- Paging area -->
    <div class="pageBox">
      <el-pagination
        background
        hide-on-single-page
        layout="total, sizes, prev, pager, next"
        :page-size="pageSize"
        :current-page="page"
        :total="total"
        @size-change="sizeChange"
        @current-change="prevNext"
        @prev-click="prevNext"
        @next-click="prevNext"
      ></el-pagination>
    </div>
  </div>

Export to Excel

Convert json data into sheet data, create a new table, insert a sheet into the table, and write the file into the table using the writeFile method of xlsx

    // Export data submit() {
      if (this.selectionList.length <= 0) {
        this.$message({
          message: "My dear, please select the data you want to export first!",
          type: "warning",
          showClose: true
        });
        return;
      }

      this.disabled = true;
      let loadingInstance = Loading.service({
        text: "My dear, please wait for a moment. I am working very hard to deal with it...",
        background: "rgba(0,0,0,.5)"
      });

      let arr = this.selectionList.map(item => {
        return {
          ID: item.id,
          Name: item.name,
          Phone: item.phone
        };
      });
      // Convert json data to sheet data let sheet = xslx.utils.json_to_sheet(arr),
      // Create a new table book = xslx.utils.book_new();
      //Insert a sheet into the table
      xslx.utils.book_append_sheet(book, sheet, "sheet1");
      // Write the file through the writeFile method of xlsx xslx.writeFile(book, `user${new Date().getTime()}.xls`);

      loadingInstance.close();
      this.disabled = false;
    }

**The above are related operations for Excele. File upload and parsing is a common requirement. If you are interested in large file upload and power-off resume, you can refer to my article Large file upload and breakpoint resume

Summarize

This is the end of this article about implementing Excel parsing and exporting functions based on Vue. For more relevant Vue Excel parsing and exporting content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • How to export the excel file returned by the backend in Vue front end
  • Vue requests the backend interface to export excel tables
  • How to use js-xlsx to export excel in vue
  • Vue encapsulates the public function method of exporting Excel data
  • Detailed implementation plan of Vue front-end exporting Excel files
  • Pitfalls and solutions when exporting excel using vue

<<:  Problems with using multiple single quotes and triple quotes in MySQL concat

>>:  How to install and configure the Docker Compose orchestration tool in Docker.v19

Recommend

Ubuntu Docker installation in vmware (container building)

1. Mind Map 2. How to build a container 2.1 Prepa...

MySQL 1130 exception, unable to log in remotely solution

Table of contents question: 1. Enable remote logi...

Solve the group by query problem after upgrading Mysql to 5.7

Find the problem After upgrading MySQL to MySQL 5...

Some tips on deep optimization to improve website access speed

<br />The website access speed can directly ...

A detailed discussion of evaluation strategies in JavaScript

Table of contents A chestnut to cover it Paramete...

3 methods to restore table structure from frm file in mysql [recommended]

When mysql is running normally, it is not difficu...

How to process blob data in MySQL

The specific code is as follows: package epoint.m...

Detailed explanation of Mysql transaction processing

1. MySQL transaction concept MySQL transactions a...

Example code for setting hot links and coordinate values ​​for web images

Sometimes you need to set several areas on a pict...

How to create and run a Django project in Ubuntu 16.04 under Python 3

Step 1: Create a Django project Open the terminal...

TypeScript installation and use and basic data types

The first step is to install TypeScript globally ...