初识Vue2.* - 与PhpSpreadsheet的小demo

Vue.js 一个流行的MVVM前端框架,数据驱动思想使得前端开发易于理解和维护。
PHPSpreadsheet 提起已经不再维护的PHPExcel,可能知道的人更多一些。PHPSpreadsheet就是PHPExcel的新项目。

刚接触Vue,结合PHPSpreadsheet做了excel和表格互转的小demo。

1、excel文件表格展示

前端代码

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <!--<meta name="viewport" content="width=device-width,initial-scale=1.0">-->
    <!-- Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
    <!--vue.js-->
    <script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
    <title>vue-excel</title>
</head>
<body>
<div class="container" style="padding-top: 60px;">
    <div class="row" id="fileForm" style="text-align: center;display:flex; display: -webkit-flex; align-items:center;">
        <div class="col-md-2 col-md-offset-2">
            <div  class="btn btn-default" v-on:click="selectFile">选择文件</div>
        </div>
        <div class="col-md-4">
            {{ fileData ? '当前选择:'+(fileData[0].name) :'未选择文件' }}
            <span v-show="upStatus" style="margin-left: 32px;color: #00CC00;">【 {{ upStatus }} 】</span>
        </div>
        <div class="col-md-2">
            <div v-on:click="upload" class="btn btn-default">提交</div>
        </div>
        <input type="file" id="upfile" name="file" @change="tirggerFile($event)" v-show="false">
    </div>

    <div class="row" v-if="load" id="table">
        <div style="padding:36px 0;text-align:center;font-size: 22px;">
            {{ name }}
        </div>
        <table class="table">
            <tr>
                <th v-for="title in titles">{{ title }}</th>
            </tr>
            <tr v-for="row in excel">
                <td v-for="val in row">{{ val }}</td>
            </tr>
        </table>
    </div>
</div>
</body>
</html>
<script>
    var ExcelFile = new Vue({
        el: "#fileForm",
        data: {
            upStatus: false,
            fileData: false,
            text: 'nihao '
        },
        methods:{
            selectFile: function () {
                upfile.click();
            },
            tirggerFile : function (event) {
                this.fileData = event.target.files;
                this.upStatus = '未上传';
            },
            upload:function () {
                let formData = new FormData();
                let docName = this.fileData[0].name;
                formData.append("file", this.fileData[0]);
                $.ajax({
                    url: "./index.php",
                    type: "POST",
                    data: formData,
                    async: true,
                    processData: false,
                    contentType: false,
                    dataType: "json",
                    beforeSend:function(){
                        ExcelFile.upStatus = '正在上传...';
                    },
                    success: function (data) {
                        if (data.code != 200){
                            ExcelFile.upStatus = data.msg;
                            alert(data.msg);
                            return;
                        }
                        ExcelFile.upStatus = '已上传';
                        // PHPSpreadsheet返回的是关联数组,JSON后为对象
                        table.titles = data.result[1];
                        delete data.result[1];
                        table.excel = data.result;
                        table.name = docName;
                        table.load = true;
                        console.log('success');
                    },
                    error: function (data) {
                        ExcelFile.upStatus = '上传失败';
                        alert('上传失败');
                    }
                });
                return false;
            }
        }
    });

    var table = new Vue({
        el:'#table',
        data:{
            name: '',
            load:false,
            titles:null,
            excel:null
        },
        methods:{
        }
    });
</script>

后端代码

<?php
require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;

function reJson($code=200,$msg='',$result=[]){
    $data['code'] = $code;
    $data['msg'] = $msg;
    $data['result'] = $result;
    echo json_encode($data);
    die;
}

if (!isset($_FILES["file"]))  reJson(204,'未上传文件');
if ($_FILES["file"]["error"] > 0) reJson(204,'文件上传出错');
// 这里只接收 xsl 和 xsls 文档,PhpSpreadsheet支持更多格式,自行处理
if (!($_FILES["file"]["type"] == 'application/vnd.ms-excel' || $_FILES["file"]["type"] == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')) reJson(204,'文件类型不符');

$inputFileName = $_FILES["file"]["tmp_name"];
// PhpSpreadsheet能够自动识别文档类型
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($inputFileName);
$sheetData = $spreadsheet->getActiveSheet()->toArray(null, true, true, true);
reJson(200,'ok',$sheetData);

2、填写表单生成excel文件

前端代码

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <!--<meta name="viewport" content="width=device-width,initial-scale=1.0">-->
    <!-- Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
    <title>vue-excel</title>
</head>
<body>
<div class="container" style="padding-top: 60px;">
    <div class="table-responsive" id="tableDiv">
        <form action="./output.php" method="post" id="infoForm">
        <table class="table table-striped table-bordered table-hover">
            <tr>
                <th>姓名</th>
                <th>性别</th>
                <th>身高</th>
                <th>体重</th>
                <th>体积</th>
                <th>表面积</th>
            </tr>
            <tr v-for="info in infos">
                <td><input class="form-control" type="text" name="name[]" v-model="info.name"></td>
                <td><input class="form-control" type="text" name="sex[]" v-model="info.sex"></td>
                <td><input class="form-control" type="text" name="height[]" v-model="info.height"></td>
                <td><input class="form-control" type="text" name="weight[]" v-model="info.weight"></td>
                <td><input class="form-control" type="text" name="volume[]" v-model="info.volume"></td>
                <td><input class="form-control" type="text" name="proportion[]" v-model="info.proportion"></td>
            </tr>
        </table>
        </form>
        <div style="margin: 22px auto;text-align: center;" >
            <div class="btn btn-success btn-lg" @click="add" style="margin: 0 16px;">新增</div>
            <div class="btn btn-primary btn-lg" @click="submit" style="margin: 0 16px;">提交</div>
        </div>
    </div>
</div>
</body>
</html>
<script>
    var table = new Vue({
        el: "#tableDiv",
        data: {
            // 表单模型
            // 直接写对象的话,用的时候要做深拷贝处理
            model: function(){
                return {
                    name:"李四",
                    sex:1,
                    height: 176,
                    weight: 66,
                    volume: 128,
                    proportion: 90
                };
            },
            infos : []
        },
        methods: {
            add: function () {
                this.infos.push(this.model());
            },
            submit:function () {
                infoForm.submit()
            }
        },
        mounted:function() {
            this.infos.push(this.model());
        }
    });
</script>

后端代码

<?php
require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\IOFactory;
$spreadsheet = new Spreadsheet();
$spreadsheet->setActiveSheetIndex(0);
$spreadsheet->getActiveSheet()->setTitle('infos');
$titles = [
        'name' =>'姓名',
        'sex' =>'性别',
        'height' =>'身高',
        'weight' =>'体重',
        'volume' =>'体积',
        'proportion' =>'表面积'
    ];
$azs = range('A','Z');
$datas = $_POST;
// 写入表格数据
$i = 0;
foreach ($titles as $name => $title) {
    $spreadsheet->getActiveSheet()->setCellValue(($azs[$i]).'1', $title);
    foreach ($datas[$name] as $n => $val) {
        $spreadsheet->getActiveSheet()->setCellValue(($azs[$i]).($n+2), $val);
    }
    ++$i;
}

header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="test.xlsx"');
$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save('php://output');

JQ写习惯了,在写新增行的时候,惯性思维想写个模板追加过去。后来发现这样就违背了MVVM的思想,失去了扩展性和对数据的管理。在数据驱动下,我们只要对数据对象进行操作(如:排序),视图就会响应数据。可以使前端开发更为专注高效。
PHPSpreadsheet 可以去下载或者使用composer安装

//composer.json
{
    "require": {
        "phpoffice/phpspreadsheet": "^1.2"
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,122评论 6 505
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,070评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,491评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,636评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,676评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,541评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,292评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,211评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,655评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,846评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,965评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,684评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,295评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,894评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,012评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,126评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,914评论 2 355