Home > php教程 > php手册 > php利用PHPExcel类导出导入Excel用法

php利用PHPExcel类导出导入Excel用法

WBOY
Release: 2016-05-25 16:39:54
Original
1244 people have browsed it

PHPExcel类是php一个excel表格处理插件了,下面我来给大家介绍利用PHPExcel类来导入与导出excel表格的应用方法,有需要了解的朋友不防参考参考,PHPExcel自己百度下载这里不介绍了.

导出Excel用法,代码如下:

<?php
//设置环境变量(新增PHPExcel) 
set_include_path(&#39;.&#39;. PATH_SEPARATOR . Yii::app()->basePath.&#39;/lib/PHPExcel&#39; . PATH_SEPARATOR . 
get_include_path());   
//注:在yii中,也可以直接Yii::import("application.lib.PHPExcel.*");   
//引入PHPExcel相关文件   
require_once "PHPExcel.php";   
require_once &#39;PHPExcel/IOFactory.php&#39;;   
require_once &#39;PHPExcel/Writer/Excel5.php&#39;;  
//把要导出的内容放到表格,新建    
$resultPHPExcel = new PHPExcel(); 
//设置参数 设值    
$resultPHPExcel->getActiveSheet()->setCellValue(&#39;A1&#39;, &#39;季度&#39;);  
$resultPHPExcel->getActiveSheet()->setCellValue(&#39;B1&#39;, &#39;名称&#39;);  
$resultPHPExcel->getActiveSheet()->setCellValue(&#39;C1&#39;, &#39;数量&#39;);  
$i = 2; 
foreach($data as $item){  
    $resultPHPExcel->getActiveSheet()->setCellValue(&#39;A&#39; . $i, $item[&#39;quarter&#39;]);  
    $resultPHPExcel->getActiveSheet()->setCellValue(&#39;B&#39; . $i, $item[&#39;name&#39;]);  
    $resultPHPExcel->getActiveSheet()->setCellValue(&#39;C&#39; . $i, $item[&#39;number&#39;]);  
    $i ++;  
}
?>
Copy after login

设置导出参数,代码如下:

<?php
//设置导出文件名  
$outputFileName = &#39;total.xls&#39;;  
$xlsWriter = new PHPExcel_Writer_Excel5($resultPHPExcel);  
//ob_start(); ob_flush();  
header("Content-Type: application/force-download");  
header("Content-Type: application/octet-stream");  
header("Content-Type: application/download");  
header(&#39;Content-Disposition:inline;filename="&#39;.$outputFileName.&#39;"&#39;);  
header("Content-Transfer-Encoding: binary");  
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");  
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");  
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");  
header("Pragma: no-cache");  
$xlsWriter->save( "php://output" ); 
输出有错,默认$xlsWriter->save( "php://output" );可能因为缓存不够大,而显示不完整,所以做个中转,代码如下:
$finalFileName = (Yii::app()->basePath.&#39;/runtime/&#39;.time().&#39;.xls&#39;;  
$xlsWriter->save($finalFileName);  
echo file_get_contents($finalFileName); 
?>
Copy after login

//file_get_contents() 函数把整个文件读入一个字符串中。和 file() 一样,不同的是 file_get_contents() 把文件读入一个字符串。

导入Excel用法,代码如下:

<?php 
if($_POST[&#39;leadExcel&#39;] == "true") 
{ 
    $filename = $_FILES[&#39;inputExcel&#39;][&#39;name&#39;]; 
    $tmp_name = $_FILES[&#39;inputExcel&#39;][&#39;tmp_name&#39;]; 
    $msg = uploadFile($filename,$tmp_name); 
    echo $msg; 
} 
//导入Excel文件 
function uploadFile($file,$filetempname)  
{ 
    //自己设置的上传文件存放路径 
    $filePath = &#39;upFile/&#39;; 
    $str = "";    
    //下面的路径按照你PHPExcel的路径来修改 
    require_once &#39;../PHPExcel/PHPExcel.php&#39;; 
    require_once &#39;../PHPExcel/PHPExcel/IOFactory.php&#39;; 
    require_once &#39;../PHPExcel/PHPExcel/Reader/Excel5.php&#39;; 
    //注意设置时区 
    $time=date("y-m-d-H-i-s");//去当前上传的时间  
    //获取上传文件的扩展名 
    $extend=strrchr ($file,&#39;.&#39;); 
    //上传后的文件名 
    $name=$time.$extend; 
    $uploadfile=$filePath.$name;//上传后的文件名地址  
    //move_uploaded_file() 函数将上传的文件移动到新位置。若成功,则返回 true,否则返回 false。 
    $result=move_uploaded_file($filetempname,$uploadfile);//假如上传到当前目录下 
    //echo $result; 
    if($result) //如果上传文件成功,就执行导入excel操作 
    { 
        include "conn.php"; 
        $objReader = PHPExcel_IOFactory::createReader(&#39;Excel5&#39;);//use excel2007 for 2007 format  
        $objPHPExcel = $objReader->load($uploadfile);  
        $sheet = $objPHPExcel->getSheet(0);  
        $highestRow = $sheet->getHighestRow();           //取得总行数  
        $highestColumn = $sheet->getHighestColumn(); //取得总列数 
        /* 第一种方法 
        //循环读取excel文件,读取一条,插入一条 
        for($j=1;$j<=$highestRow;$j++)                        //从第一行开始读取数据 
        {  
            for($k=&#39;A&#39;;$k<=$highestColumn;$k++)            //从A列读取数据 
            {  
                // 
                这种方法简单,但有不妥,以&#39;&#39;合并为数组,再分割为字段值插入到数据库 
                实测在excel中,如果某单元格的值包含了导入的数据会为空         
                // 
                $str .=$objPHPExcel->getActiveSheet()->getCell("$k$j")->getValue().&#39;&#39;;//读取单元格 
            }  
            //echo $str; die(); 
            //explode:函数把字符串分割为数组。 
            $strs = explode("",$str); 
            $sql = "INSERT INTO te(`1`, `2`, `3`, `4`, `5`) VALUES ( 
            &#39;{$strs[0]}&#39;, 
            &#39;{$strs[1]}&#39;, 
            &#39;{$strs[2]}&#39;, 
            &#39;{$strs[3]}&#39;, 
            &#39;{$strs[4]}&#39;)"; 
            //die($sql); 
            if(!mysql_query($sql)) 
            { 
                return false; 
                echo &#39;sql语句有误&#39;; 
            } 
            $str = ""; 
        }   
        unlink($uploadfile); //删除上传的excel文件 
        $msg = "导入成功!"; 
        */ 
        /* 第二种方法*/ 
        $objWorksheet = $objPHPExcel->getActiveSheet(); 
        $highestRow = $objWorksheet->getHighestRow();  
        echo &#39;highestRow=&#39;.$highestRow; 
        echo "<br>"; 
        $highestColumn = $objWorksheet->getHighestColumn(); 
        $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);//总列数 
        echo &#39;highestColumnIndex=&#39;.$highestColumnIndex; 
        echo "<br>"; 
        $headtitle=array();  
        for ($row = 1;$row <= $highestRow;$row++)  
        { 
            $strs=array(); 
            //注意highestColumnIndex的列数索引从0开始 
            for ($col = 0;$col < $highestColumnIndex;$col++) 
            { 
                $strs[$col] =$objWorksheet->getCellByColumnAndRow($col, $row)->getValue(); 
            }     
            $sql = "INSERT INTO te(`1`, `2`, `3`, `4`, `5`) VALUES ( 
            &#39;{$strs[0]}&#39;, 
            &#39;{$strs[1]}&#39;, 
            &#39;{$strs[2]}&#39;, 
            &#39;{$strs[3]}&#39;, 
            &#39;{$strs[4]}&#39;)"; 
            //die($sql); 
            if(!mysql_query($sql)) 
            { 
                return false; 
                echo &#39;sql语句有误&#39;; 
            } 
        } 
    } 
    else 
    { 
       $msg = "导入失败!"; 
    }  
    return $msg; 
}
?>
Copy after login

HTML网页代码,代码如下:

<form action="upload.php" method="post" enctype="multipart/form-data"> 
<input type="hidden" name="leadExcel" value="true"> 
<table align="center" width="90%" border="0"> 
<tr> 
   <td> 
    <input type="file" name="inputExcel"><input type="submit" value="导入数据"> 
   </td> 
</tr> 
</table> 
</form>
Copy after login


文章链接:

随便收藏,请保留本文地址!

source:php.cn
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template