How to use JavaScript to implement front-end import and export excel files (H5 editor actual combat review)

Preface

Recently, the author has finally completed the preliminary establishment of the H5-Dooring background management system, and has preliminary data collection and data analysis capabilities. Next, we will review several knowledge points involved and explain its visualization in Dooring H5. The solution in the editor. The author will be divided into 3 articles to review, the main solution scenarios are as follows:

  • How to use JavaScript to implement front-end import and export excel files (H5 editor actual combat review)

  • How the front-end generates a multi-dimensional data visualization analysis report based on the data in the table with one click

  • How to realize the authority routing and authority menu under the member management system

The above scenarios are also the problems that front-end engineers often encounter or will encounter in the development of back-end management systems. This article is the first article in the above introduction. You will gain:

  • Use JavaScript to import excel files at the front end and automatically generate editable Table components

  • Use JavaScript to achieve one-click export of excel files based on Table data

  • Basic use of XLSX and js-export-excel

text

The following content materials in this article are all based on the screenshots of the H5 visual editor (H5-Dooring) project. If you want to have an actual experience, you can visit the actual experience of the H5-Dooring website. Next we will directly start our solution.

1. Use JavaScript to import excel files and automatically generate editable Table components

Before starting to achieve, let's take a look at the implementation effect.

1.1 Realization effect

Import the excel file and render the table through the table component of antd:   Edit the table component:   Render the visualization chart in real time after saving the table data: The   above is the complete process of importing the excel file, editing the table, and finally dynamically generating the chart.

1.2 Realize one-click import excel file and generate table form

For the function of importing excel files, we can use javascript native way to realize parsing, for example, we can use the native APIs of fileReader, but considering the development efficiency and later maintenance, the author uses antd's Upload component and XLSX to realize the function of uploading files and parsing. Since we use the table component of antd to render data, we need to manually convert the parsed data into a data format supported by the table. The general process is as follows:   so all we need to do is to pass the file data obtained by Upload to xlsx, by xlsx generates analytic objects, and finally we use javascript algorithm to process xlsx objects into data formats supported by ant-table. Here we use FileReader object, the purpose is to convert the file to BinaryString, and then we can use xlsx binary mode To read the excel data, the code is as follows:

// 解析并提取excel数据
let reader = new FileReader();
reader.onload = function(e) {
  let data = e.target.result;
  let workbook = XLSX.read(data, {type: 'binary'});
  let sheetNames = workbook.SheetNames; // 工作表名称集合
  let draftObj = {}
  sheetNames.forEach(name => {
    // 通过工作表名称来获取指定工作表
    let worksheet = workbook.Sheets[name]; 
    for(let key in worksheet) {
      // v是读取单元格的原始值
      if(key[0] !== '!') {
        if(draftObj[key[0]]) {
          draftObj[key[0]].push(worksheet[key].v)
        }else {
          draftObj[key[0]] = [worksheet[key].v]
        }
      }
    }
  });
  // 生成ant-table支持的数据格式
  let sourceData = Object.values(draftObj).map((item,i) => ({ key: i + '', name: item[0], value: item[1]}))

复制代码

After the above processing, the sourceData we get is the data structure available for ant-table, so far we have realized the function of table import.

1.3 Realization of editing function of table

The editing function of the table is actually very simple. We only need to follow the implementation of the custom rows and cells provided by the antd table component. There are also implementations of editable tables on the antd official website, as follows:   everyone is interested You can study the following privately. Of course, it is very easy to implement editable tables yourself, and there are many ways, such as using the column render function to dynamically switch the editing state of the table, or using pop-up editing, etc. are all possible.

1.4 Dynamically generate charts based on edited table data

Dynamically generating charts based on table data requires certain conventions. We need to comply with the data specifications of the chart library. However, we have table data. Processing data specifications is of course a very simple matter. The author's visualization library is implemented by antv's f2 , So a layer of adaptation is needed to enable f2 to consume our data.

Another point is that in order to be able to use multiple charts, we need to encapsulate the f2 chart uniformly to make it a visual component library that meets our application scenarios. Let's first look at the data format used by f2:

const data = [
  { genre: 'Sports', sold: 275 },
  { genre: 'Strategy', sold: 115 },
  { genre: 'Action', sold: 120 },
  { genre: 'Shooter', sold: 350 },
  { genre: 'Other', sold: 150 }
];

复制代码

This data format will be rendered into the following chart:   So we have summarized its main two latitude indicators, including their area chart, pie chart, and line chart. The format is basically the same, so we can encapsulate it into components based on this. The visual components are as follows:

import { Chart } from '@antv/f2';
import React, { memo, useEffect, useRef } from 'react';
import ChartImg from '@/assets/chart.png';

import styles from './index.less';
import { IChartConfig } from './schema';

interface XChartProps extends IChartConfig {
  isTpl: boolean;
}

const XChart = (props: XChartProps) => {
  const { isTpl, data, color, size, paddingTop, title } = props;
  const chartRef = useRef(null);
  useEffect(() => {
    if (!isTpl) {
      const chart = new Chart({
        el: chartRef.current || undefined,
        pixelRatio: window.devicePixelRatio, // 指定分辨率
      });

      // step 2: 处理数据
      const dataX = data.map(item => ({ ...item, value: Number(item.value) }));

      // Step 2: 载入数据源
      chart.source(dataX);

      // Step 3:创建图形语法,绘制柱状图,由 genre 和 sold 两个属性决定图形位置,genre 映射至 x 轴,sold 映射至 y 轴
      chart
        .interval()
        .position('name*value')
        .color('name');

      // Step 4: 渲染图表
      chart.render();
    }
  }, [data, isTpl]);
  return (
    <div className={styles.chartWrap}>
      <div className={styles.chartTitle} style={
    
    { color, fontSize: size, paddingTop }}>
        {title}
      </div>
      {isTpl ? <img src={ChartImg} alt="dooring chart" /> : <canvas ref={chartRef}></canvas>}
    </div>
  );
};

export default memo(XChart);

复制代码

Of course, other visual components can also be encapsulated in the same mode, so I won't give an example one by one. The above component encapsulation uses react's hooks component, and vue's is similar, and the basic principles are the same.

2. Use JavaScript to achieve one-click export of excel files based on Table data at the front end

In the same way, we realized that one-click export of table data to excel is similar, but the scheme is different, let's take a look at the implementation effect in Dooring.

2.1 One-click export to excel to achieve the effect

   The above is the process for the user to export the excel file with one click based on the data collected in the background.The last picture is the presentation of the generated excel file in the office software.

2.2 Use javascript to realize one-click export excel file function

The one-click export function is mainly used in the background management page of H5-Dooring to provide users with a convenient ability to export data. The export function here can still be implemented using xlsx, but after a comprehensive comparison, the author found that there is a simpler solution. Next, the author will introduce in detail. First, let's take a look at the process:   obviously our export process is much simpler than the import process, we only need to decompile the data format of the table into the data supported by the plug-in. Here the author uses js -export-excel to do file export, using it is very flexible, we can customize:

  • Customize the exported excel file name

  • Custom excel filter field

  • Customize the header name of each column in the excel file

Since the data structure supported by js-export-excel is an array object, we need to spend a little effort to convert the table data into an array object. It should be noted that the value corresponding to the key in the ant table data structure can be an array, but js The value corresponding to the -export-excel key is a string, so we need to convert the array into a string, such as [a,b,c] becomes'a,b,c', so we need to convert the data format, specifically The implementation is as follows:

const generateExcel = () => {
    let option = {};  //option代表的就是excel文件
    let dataTable = [];  //excel文件中的数据内容
    let len = list.length;
    if (len) {
        for(let i=0; i<len; i++) {
            let row = list[i];
            let obj:any = {};
            for(let key in row) {
                if(typeof row[key] === 'object') {
                    let arr = row[key];
                    obj[key] = arr.map((item:any) => (typeof item === 'object' ? item.label : item)).join(',')
                }else {
                    obj[key] = row[key]
                }
            }
            dataTable.push(obj);  //设置excel中每列所获取的数据源
        }
    }
    let tableKeys = Object.keys(dataTable[0]);
    option.fileName = tableName;  //excel文件名称
    option.datas = [
          {
            sheetData: dataTable,  //excel文件中的数据源
            sheetName: tableName,  //excel文件中sheet页名称
            sheetFilter: tableKeys,  //excel文件中需显示的列数据
            sheetHeader: tableKeys,  //excel文件中每列的表头名称
          }
    ]
    let toExcel = new ExportJsonExcel(option);  //生成excel文件
    toExcel.saveExcel();  //下载excel文件
  }

复制代码

 Note that the above solution implemented by the author can be used for any table component, and the above code can be used directly in most scenarios. So far, we have implemented the front-end import and export excel file function using JavaScript.

So, are you knowledgeable again today?

At last

The author of the above tutorial has been integrated into H5-Dooring. For some more complex interactive functions, it can also be realized through reasonable design. You can explore and study by yourself.

github????: H5 online editor H5-Dooring

Or scan the QR code below to access:

If you want to learn more H5 games, webpack, node, gulp, css3, javascript, nodeJS, canvas data visualization and other front-end knowledge and actual combat, welcome to study and discuss together in "Interesting Frontend" to explore the front-end boundary together.

Comment area

Finally, if you still have more energy, you can click to read the original text and continue to fill in the form~

Guess you like

Origin blog.csdn.net/KlausLily/article/details/109108425
Recommended