Home  >  Article  >  Web Front-end  >  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)

不言
不言forward
2019-01-24 09:28:416191browse

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

2. Introduce

import * as XLSX from 'xlsx'

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
}

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')//导出的文件名
}

3. Bind the event

<button>导出Excel</button>

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]);
}

2. Bind events

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

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;
}

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:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete