您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

ThinkPHP和phpExcel实现异步多文件导入

2026/3/17 11:48:28发布13次查看
thinkphp+phpexcel和jqueryfileupload结合使用实现异步多文件导入
使用中发现一个小问题,上传的文件不知道跑到哪里去了,有知道的同学麻烦告知一下,⊙﹏⊙b汗
本程序基于thinkphp 3.1.3开发,支持excel2003和excel2007上传,有兴趣的朋友可以自行在高版本上进行研究
多文件使用方法:在选择文件的时候按住ctrl键,用鼠标点击文件即可。
首先,分享excel导入和输出的函数,在common文件夹下的common.php文件中//excel输出
function exportexcel($exptitle,$expcellname,$exptabledata){
    $xlstitle = iconv('utf-8', 'gb2312', $exptitle);//文件名称
    $filename = iconv('utf-8', 'gb2312', $exptitle).date('_ymdhis');//or $xlstitle 文件名称可根据自己情况设定
    $cellnum = count($expcellname);
    $datanum = count($exptabledata);
    import(class.phpexcel.phpexcel,app_path);
    import(class.phpexcel.writer.excel5,app_path);
    import(class.phpexcel.writer.excel2007,app_path);
    $objphpexcel = new phpexcel();
    $cellname = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','aa','ab','ac','ad','ae','af','ag','ah','ai','aj','ak','al','am','an','ao','ap','aq','ar','as','at','au','av','aw','ax','ay','az');
$objphpexcel->getactivesheet(0)->mergecells('a1:'.$cellname[$cellnum-1].'1');//合并单元格
    $objphpexcel->setactivesheetindex(0)->setcellvalue('a1', $exptitle.'  导出时间:'.date('y-m-d h:i:s'));
    for($i=0;$i        $objphpexcel->setactivesheetindex(0)->setcellvalue($cellname[$i].'2', $expcellname[$i][1]);
    }
    // miscellaneous glyphs, utf-8
    for($i=0;$i        for($j=0;$j            $objphpexcel->getactivesheet(0)->setcellvalue($cellname[$j].($i+3), $exptabledata[$i][$expcellname[$j][0]]);
        }
    }
header('pragma:public');
    header('content-type:application/vnd.ms-excel;charset=utf-8;name='.$xlstitle.'.xls');
    header(content-disposition:attachment;filename=$filename.xls);//attachment新窗口打印inline本窗口打印
    $objwriter = phpexcel_iofactory::createwriter($objphpexcel, 'excel5');
    $objwriter->save('php://output');
    exit;
}
//excel导入
function importexcel($file){
    if(!file_exists($file)){
        return array(error=>0,'message'=>'file not found!');
    }
    //vendor(phpexcel.phpexcel.iofactory);
    import(class.phpexcel.phpexcel,app_path);
    import(class.phpexcel.writer.excel5,app_path);
    import(class.phpexcel.writer.excel2007,app_path);
//$filepath = __root__.'/public/uploads/excel/'.$savename;
    //$filepath = $savepath.$savename;
    $phpexcel = new phpexcel();
    /**默认用excel2007读取excel,若格式不对,则用之前的版本进行读取*/
    $phpreader = new phpexcel_reader_excel2007();
    if(!$phpreader->canread($file)){
        $phpreader = new phpexcel_reader_excel5();
        if(!$phpreader->canread($file)){
            $this->error(excel文件不存在!);
        }
    }
$phpexcel = $phpreader->load($file);
    $allworksheets = $phpexcel->getallsheets();  //读取所有sheets
    $i = 0;
foreach($allworksheets as $objworksheet){
        //print_r($objworksheet);die;
        $sheetname=$objworksheet->gettitle();
        //echo $objworksheet->;die;
        $allrow = $objworksheet->gethighestrow();//how many rows
        $highestcolumn = $objworksheet->gethighestcolumn();//how many columns
        $allcolumn = phpexcel_cell::columnindexfromstring($highestcolumn);
        $array[$i][title] = $sheetname;
        $array[$i][cols] = $allcolumn;
        $array[$i][rows] = $allrow;
        $arr = array();
        $ismergecell = array();
        foreach ($objworksheet->getmergecells() as $cells) {//merge cells
            foreach (phpexcel_cell::extractallcellreferencesinrange($cells) as $cellreference) {
                $ismergecell[$cellreference] = true;
            }
        }
        for($currentrow = 1 ;$currentrow            $row = array();
            for($currentcolumn=0;$currentcolumn                ;
                $cell =$objworksheet->getcellbycolumnandrow($currentcolumn, $currentrow);
                $afcol = phpexcel_cell::stringfromcolumnindex($currentcolumn+1);
                $bfcol = phpexcel_cell::stringfromcolumnindex($currentcolumn-1);
                $col = phpexcel_cell::stringfromcolumnindex($currentcolumn);
                $address = $col.$currentrow;
                $value = $objworksheet->getcell($address)->getvalue();
                if(substr($value,0,1)=='='){
                    return array(error=>0,'message'=>'can not use the formula!');
                    exit;
                }
                if($cell->getdatatype()==phpexcel_cell_datatype::type_numeric){
                    $cellstyleformat=$cell->getparent()->getstyle( $cell->getcoordinate() )->getnumberformat();
                    $formatcode=$cellstyleformat->getformatcode();
                    if (preg_match('/^([$[a-z]*-[0-9a-f]*])*[hmsdy]/i', $formatcode)) {
                        $value=gmdate(y-m-d, phpexcel_shared_date::exceltophp($value));
                    }else{
                        $value=phpexcel_style_numberformat::toformattedstring($value,$formatcode);
                    }
                }
                if($ismergecell[$col.$currentrow]&&$ismergecell[$afcol.$currentrow]&&!empty($value)){
                    $temp = $value;
                }elseif($ismergecell[$col.$currentrow]&&$ismergecell[$col.($currentrow-1)]&&empty($value)){
                    $value=$arr[$currentrow-1][$currentcolumn];
                }elseif($ismergecell[$col.$currentrow]&&$ismergecell[$bfcol.$currentrow]&&empty($value)){
                    $value=$temp;
                }
                $row[$currentcolumn] = $value;
            }
            $arr[$currentrow] = $row;
        }
        $array[$i][content] = $arr;
        $i++;
    }
    spl_autoload_register(array('think','autoload'));//must, resolve thinkphp and phpexcel conflicts
    unset($objworksheet);
    unset($phpreader);
    unset($phpexcel);
    unlink($file);
    return array(error=>1,data=>$array);
}使用thinkphp自带的上传功能进行处理//上传处理
    public function up(){
        import('org.net.uploadfile');
        $upload = new uploadfile();// 实例化上传类
        $upload->maxsize  = 3145728 ;// 设置附件上传大小
        $upload->allowexts  = array('xls', 'xlsx');// 设置附件上传类型
        $savepath = $upload->savepath =  './upload/excel/';// 设置附件上传目录
        if(!$upload->upload()) {// 上传错误提示错误信息
            $this->error($upload->geterrormsg());
        }else{// 上传成功 获取上传文件信息
            $info =  $upload->getuploadfileinfo();
        }
        $savename = $info[0]['savename'];
        $data = importexcel($savepath.'/'.$savename);
        //echo $savepath.'/'.$savename;die;
        $this->ajaxreturn($data);
    }模板的js代码$(function () {
    'use strict';
    // change this to the location of your server-side upload handler:
    var url = window.location.hostname === 'blueimp.github.io' ? '//jquery-file-upload.appspot.com/' : {:u('index/up')};
    $('#fileupload').fileupload({
        url: url,
        datatype: 'json',
        done: function (e, data) {
            $.each(data.result.data, function (index, file) {
                $.each(file.content,function(i,v){
                    var str = ;
                    $.each(v,function(a,b){
                        //b = b?b:'';
                        if(b==null){
                            b=;
                        }
                        str += +b+ ;
                    })
                    $(
).html(str).appendto('#files');    
                });
                //$('
').text(file.cols).appendto('#files');
            });
        },
        progressall: function (e, data) {
            var progress = parseint(data.loaded / data.total * 100, 10);
            $('#progress .progress-bar').css(
                'width',
                progress + '%'
            );
        }
    }).prop('disabled', !$.support.fileinput)
        .parent().addclass($.support.fileinput ? undefined : 'disabled');
});最后附上一张上传后的效果图
源代码已经分享到qq交流群,有需要的朋友可加群下载
qq交流群:282882201
有的朋友会问:下面的图片是干嘛的,嘿嘿,我也不知道干嘛的,你看着办吧嘿嘿。如果觉得本文没用,忽略即可。
ad:真正免费,域名+虚机+企业邮箱=0元
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product