zoukankan      html  css  js  c++  java
  • 纯前端实现导入导出功能excel

    这里的的语法是react,不过vue也可以使用

    1.首先下载xlsx插件 (我用npm下载有问题,所以这里用的yarn)

    npm install xlsx

    yarn add xlsx

    2.创建一个空的js文件 excel.js,这里是通用的导入导出的js方法

    import XLSX from "xlsx"
    
    // 导入excel的函数
    const importsExcel=(file)=>{
        //使用promise导入
      return  new Promise((resolve,reject)=>{
         // 获取上传的文件对象
         const { files } = file.target; //获取里面的所有文件
         // 通过FileReader对象读取文件
         const fileReader = new FileReader();
     
         fileReader.onload = event => { //异步操作  excel文件加载完成以后触发
             try {
                 const { result } = event.target;
                 // 以二进制流方式读取得到整份excel表格对象
                 const workbook = XLSX.read(result, { type: 'binary' });
                 let data = []; // 存储获取到的数据
                 // 遍历每张工作表进行读取(这里默认只读取第一张表)
                 for (const sheet in workbook.Sheets) {
                     if (workbook.Sheets.hasOwnProperty(sheet)) {
                          data = data.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]));
                     }
                 }
                 resolve(data);//导出数据
             } catch (e) {
                 // 这里可以抛出文件类型错误不正确的相关提示
                reject("失败");//导出失败
             }
         };
         // 以二进制方式打开文件
         fileReader.readAsBinaryString(files[0]);
      })
    }
    
    // 导出excel的函数
    
    const  exportExcel =(headers, data, fileName = 'demo.xlsx')=>{
        const _headers = headers
        .map((item, i) => Object.assign({}, { key: item.key, title: item.title, position: String.fromCharCode(65 + i) + 1 }))
        .reduce((prev, next) => Object.assign({}, prev, { [next.position]: { key: next.key, v: next.title } }), {});
        const _data = data
        .map((item, i) => headers.map((key, j) => Object.assign({}, { content: item[key.key], position: String.fromCharCode(65 + j) + (i + 2) })))
        // 对刚才的结果进行降维处理(二维数组变成一维数组)
        .reduce((prev, next) => prev.concat(next))
        // 转换成 worksheet 需要的结构
        .reduce((prev, next) => Object.assign({}, prev, { [next.position]: { v: next.content } }), {});
     
        // 合并 headers 和 data
        const output = Object.assign({}, _headers, _data);
        // 获取所有单元格的位置
        const outputPos = Object.keys(output);
        // 计算出范围 ,["A1",..., "H2"]
        const ref = `${outputPos[0]}:${outputPos[outputPos.length - 1]}`;
        
        // 构建 workbook 对象
        const wb = {
            SheetNames: ['mySheet'],
            Sheets: {
                mySheet: Object.assign(
                    {},
                    output,
                    {
                        '!ref': ref,
                        '!cols': [{ wpx: 45 }, { wpx: 100 }, { wpx: 200 }, { wpx: 80 }, { wpx: 150 }, { wpx: 100 }, { wpx: 300 }, { wpx: 300 }],
                    },
                ),
            },
        };
     
    // 导出 Excel
    XLSX.writeFile(wb, fileName);
     
    }
     
     
    export  { importsExcel,exportExcel }
    

    3.这里是用react写的,具体看代码吧

    import React, { Component } from 'react'
    import { importsExcel,exportExcel } from '../until/excel'
    export class ExcelData extends Component {
        state = {
            header:[
                {title: '编号',dataIndex: 'id',key: 'id',className: 'text-monospace'},
                {title: '用户名称',dataIndex: 'username',key: 'username',},
                {title: '用户年龄',dataIndex: 'userage',key: 'userage',}
            ],
            exportData:[
                {id:1,username:"张三",userage:18},
                {id:2,username:"李四",userage:30},
                {id:3,username:"王五",userage:19}
            ]
        }
        onChange = (e) => {
            importsExcel(e).then(res=>{
            console.log("res",res)
                // 上传成功
            }).catch(err=>{
    
            })
        }
        
        exportList = () =>{
            // 这里是模拟的假数据,具体的可以根据后端返回的数据
            const {header,exportData} = this.state
            exportExcel(header,exportData,"学生信息.xlsx")
        }
        render() {
            return (
                <div>
                    导入学生表:<input type="file" accept =".xls,.xlsx" onChange={this.onChange}></input>
                    <br></br>
                    导出学生表:<button onClick={ this.exportList }>导出</button>
                </div>
            )
        }
    }
    
    export default ExcelData
    

      

    努力才会有收获,坚持才会成功。
  • 相关阅读:
    Android Studio代码自己主动检測错误提示
    uva 1567
    UWP 新手教程2——怎样实现自适应用户界面
    远程服务的使用场景
    本地服务和远程服务
    本地应用调用远程服务中的方法
    混合方式开启服务
    绑定服务抽取接口
    绑定服务调用服务里的方法
    bind绑定服务的生命周期
  • 原文地址:https://www.cnblogs.com/97Coding/p/14870405.html
Copyright © 2011-2022 走看看