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[0]['numRows']; $i++) {

echo "<tr>";

for ($j = 1; $j <= $data->sheets[0]['numCols']; $j++) {

echo "<td style='border:1px solid #ccc'>";

echo $data->sheets[0]['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[0]['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[0])){

$start=$start[0];

}else{

$start=0;

}

for($i=$start;$i<$count+$start;$i++){

$sum=count($arr[$i]);

$start1=array_keys($arr[$i]);

if(is_numeric($start1[0])){

$start1=$start1[0];

}else{

$start1=0;

}

for($j=$start1;$j<$sum+$start1;$j++){

echo $arr[$i][$j]."\t";

}

echo "\n";

}

}

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值