小雨点点789 发表于 2017-3-27 09:50:30

php读写excel类函数

因为项目要用到读写excel文件,结果在网上找了半天没有找到一个满意的,所以自己只好写一个,下面把代码分享给大家。
<?php
ob_start();
require_once 'phpExcelReader/Excel/reader.php';//在读取excel时需要一个phpExcelReader类包,自己可以在网上搜索下载
$wr_excel=new wr_excel();
//$wr_excel->read_excel("test.xls");
//$wr_excel->write_excel($wr_excel->back_excel_arr("test.xls"));
//exit();
$arr=array(0=>array(0=>"姓名",1=>"密码",2=>"性别"),1=>array(0=>"小明",1=>"123123",2=>"男"));
$wr_excel->write_excel($arr);

class wr_excel{//读写类
function read_excel($filepath){//读写excel文件并且以表格形式在网页上显示
$data = new Spreadsheet_Excel_Reader();
$data->setOutputEncoding('utf-8');
$data->read($filepath);
echo"<table cellSpacing=0;cellPadding=0>";
for ($i = 1; $i <= $data->sheets['numRows']; $i++) {
echo "<tr>";
for ($j = 1; $j <= $data->sheets['numCols']; $j++) {
echo "<td style='border:1px solid #ccc'>";
echo $data->sheets['cells'][$i][$j];
echo "</td>";
}
echo "</tr>";
}
echo"</table>";
}

function back_excel_arr($filepath){//读取excel文件将其内容以二维数组形式返回
$data = new Spreadsheet_Excel_Reader();
//设置文本输出编码
$data->setOutputEncoding('utf-8');
//读取Excel文件
$data->read($filepath);
return $data->sheets['cells'];
}
function write_excel($arr){//将$arr以导入到一个excel文件中保存,$arr一定要是个二维数组
header("Content-type:application/vnd.ms-excel"); //如果此函数在一个单独文件中,不需要再头部加ob_start()缓冲函数,否则要加该函数
header("Content-Disposition:filename=test1.xls");
    $count=count($arr);
$start=array_keys($arr);
if(is_numeric($start)){
$start=$start;
}else{
$start=0;
}
    for($i=$start;$i<$count+$start;$i++){
   
    $sum=count($arr[$i]);
   $start1=array_keys($arr[$i]);
if(is_numeric($start1)){
$start1=$start1;
}else{
$start1=0;
}
   for($j=$start1;$j<$sum+$start1;$j++){
   echo $arr[$i][$j]."\t";
   }
   echo "\n";
    }

}

}
页: [1]
查看完整版本: php读写excel类函数