Table of Contents
Implementation of the import Excel function
Home Web Front-end JS Tutorial How to implement Excel import and export functions on the front end (code example)

How to implement Excel import and export functions on the front end (code example)

Jan 24, 2019 am 09:28 AM
html5 javascript react.js

The content this article brings to you is about how the front-end implements Excel import and export functions (code examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

In a recent project, I wanted to implement a function of importing and exporting Excel. After searching for some plug-ins, I found the js-xlsx plug-in, so I tried to use it. Here I will briefly record the usage method and the problems encountered.

SheetJS js-xlsx is a plug-in that can read and write tables in multiple formats. It has good browser support and can be used on multiple language platforms. It currently has 14k stars on github.
Plug-in address: https://github.com/SheetJS/js...

Use

1. Install dependencies

Enter Project folder, install xlsx

yarn add xlsx
Copy after login

2. Introduce

import * as XLSX from 'xlsx'
Copy after login

Export Excel function implementation into the project

1. Define what needs to be used when exporting Method

export default function download(json,fileName){
    const type = 'xlsx'//定义导出文件的格式
    var tmpDown;//导出的内容
    var tmpdata = json[0];
    json.unshift({});
    var keyMap = []; //获取keys
    for (var k in tmpdata) {
        keyMap.push(k);
        json[0][k] = k;
    }
    var tmpdata = [];//用来保存转换好的json 
    
    json.map((v, i) => keyMap.map((k, j) => Object.assign({}, {
        v: v[k],
        position: (j > 25 ? getCharCol(j) : String.fromCharCode(65 + j)) + (i + 1)
    }))).reduce((prev, next) => prev.concat(next)).forEach((v, i) => tmpdata[v.position] = {
        v: v.v
    });
    var outputPos = Object.keys(tmpdata); //设置区域,比如表格从A1到D10
    var tmpWB = {
        SheetNames: ['mySheet'], //保存的表标题
        Sheets: {
            'mySheet': Object.assign({},
                tmpdata, //内容
                {
                    '!ref': outputPos[0] + ':' + outputPos[outputPos.length - 1] //设置填充区域
                })
        }
    };
    tmpDown = new Blob([s2ab(XLSX.write(tmpWB, 
        {bookType: (type == undefined ? 'xlsx':type),bookSST: false, type: 'binary'}//这里的数据是用来定义导出的格式类型
        ))], {
        type: ""
    }); //创建二进制对象写入转换好的字节流
    saveAs(tmpDown,fileName);
}

function saveAs(obj, fileName){//导出功能实现
    var tmpa = document.createElement("a");
    tmpa.download = fileName || "下载";
    tmpa.href = URL.createObjectURL(obj); //绑定a标签
    tmpa.click(); //模拟点击实现下载
    setTimeout(function () { //延时释放
        URL.revokeObjectURL(obj); //用URL.revokeObjectURL()来释放这个object URL
    }, 100);
}

function s2ab(s){ //字符串转字符流
    var buf = new ArrayBuffer(s.length);
    var view = new Uint8Array(buf);
    for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
    return buf;
}

function getCharCol(n){
    let temCol = '',
    s = '',
    m = 0
    while (n > 0) {
        m = n % 26 + 1
        s = String.fromCharCode(m + 64) + s
        n = (n - m) / 26
    }
    return s
}
Copy after login

2. Use the export method in the project

//导出excel
//导出excel
downloadExl = () => {
    const { results } = this.props //需要导出的json数据
    let datas = _.clone(results)//这里为了不影响项目的数据的使用 采用了lodash中的深克隆方法
    let json = datas.map(item=> { //将json数据的键名更换成导出时需要的键名
        return {
            '人员ID' :item.id,
            '姓名' : item.name,
            '证件类型': this.findIdType(item.idType),//将类型代号转为汉字
            '证件号码': item.credentialsId,
            '固定电话': item.tel,
            '移动电话': item.mobile
        }
    })
    download(json,'人员信息.xlsx')//导出的文件名
}
Copy after login

3. Bind the event

<button>导出Excel</button>
Copy after login

This way you can easily Implemented the export function of Excel

Implementation of the import Excel function

1. Define the method to be used when importing

//导入excel
onImportExcel = file => {
    // 获取上传的文件对象
    const { files } = file.target;
    // 通过FileReader对象读取文件
    const fileReader = new FileReader();
    fileReader.onload = event => {
        try {
            const { result } = event.target;
            // 以二进制流方式读取得到整份excel表格对象
            const workbook = XLSX.read(result, { type: 'binary' });
            // 存储获取到的数据
            let data = [];
            // 遍历每张工作表进行读取(这里默认只读取第一张表)
            for (const sheet in workbook.Sheets) {
            // esline-disable-next-line
            if (workbook.Sheets.hasOwnProperty(sheet)) {
                // 利用 sheet_to_json 方法将 excel 转成 json 数据
                data = data.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]));
                // break; // 如果只取第一张表,就取消注释这行
            }
        }
        // 最终获取到并且格式化后的 json 数据
        const uploadData = data.map(item=> {
            return {
                id : Number(item['人员ID']),
                name : item['姓名'],
                idType: this.findIdType(item['证件类型'],'string'),
                credentialsId: item['证件号码'],
                tel: item['固定电话'],
                mobile: item['移动电话']
            }
        })
        console.log(uploadData)//这里得到了后端需要的json数据,调用接口传给后端就行了
        message.success('上传成功!') //这里用了antd中的message组件
        } catch (e) {
            // 这里可以抛出文件类型错误不正确的相关提示
            message.error('文件类型不正确!');
        }
    };
    // 以二进制方式打开文件
    fileReader.readAsBinaryString(files[0]);
}
Copy after login

2. Bind events

<button>
    导入Excel
    <input> 
    //这里对原有的input样式进行了修改,accept 属性定义了上传文件支持的类型,onChange 操作中的 importExcel 方法定义了上传文件时执行的操作。 
</button>
Copy after login

3. Modify the style

.upload_wrap {
  display: inline-block;
  position: relative;
  width: 94px;
  padding: 3px 5px;
  overflow: hidden;
}

.file_uploader {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  outline: none;
  opacity: 0;
  background-color: transparent;
}

.upload_text {
  display: inline-block;
  margin-left: 5px;
}

.upload_tip {
  display: inline-block;
  margin-left: 10px;
  color: #999;
}
Copy after login

4. Make corresponding prompts for file upload and reading results (the message component in ant design is used here) )
How to implement Excel import and export functions on the front end (code example)

5. Obtained json data

How to implement Excel import and export functions on the front end (code example)

The import and export function is implemented in this way, is it very simple?

The above is the detailed content of How to implement Excel import and export functions on the front end (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Table Border in HTML Table Border in HTML Sep 04, 2024 pm 04:49 PM

Guide to Table Border in HTML. Here we discuss multiple ways for defining table-border with examples of the Table Border in HTML.

HTML margin-left HTML margin-left Sep 04, 2024 pm 04:48 PM

Guide to HTML margin-left. Here we discuss a brief overview on HTML margin-left and its Examples along with its Code Implementation.

Nested Table in HTML Nested Table in HTML Sep 04, 2024 pm 04:49 PM

This is a guide to Nested Table in HTML. Here we discuss how to create a table within the table along with the respective examples.

HTML Table Layout HTML Table Layout Sep 04, 2024 pm 04:54 PM

Guide to HTML Table Layout. Here we discuss the Values of HTML Table Layout along with the examples and outputs n detail.

HTML Input Placeholder HTML Input Placeholder Sep 04, 2024 pm 04:54 PM

Guide to HTML Input Placeholder. Here we discuss the Examples of HTML Input Placeholder along with the codes and outputs.

HTML Ordered List HTML Ordered List Sep 04, 2024 pm 04:43 PM

Guide to the HTML Ordered List. Here we also discuss introduction of HTML Ordered list and types along with their example respectively

Moving Text in HTML Moving Text in HTML Sep 04, 2024 pm 04:45 PM

Guide to Moving Text in HTML. Here we discuss an introduction, how marquee tag work with syntax and examples to implement.

HTML onclick Button HTML onclick Button Sep 04, 2024 pm 04:49 PM

Guide to HTML onclick Button. Here we discuss their introduction, working, examples and onclick Event in various events respectively.

See all articles