作为一个原本的java党,用过php才知道,原来对于excel文件的写入和读取原来可以这么简单!
利用php实现对于excel的读取,主要借助于phpexcel插件来完成。
phpexcel下载地址:phpexcel下载
一、phpexcel实现写入excel操作步骤
首先需要引入类文件,引入phpexcel.php文件。
1、新建一个excel表格(实例化phpexcel类)
2、创建sheet(内置表) (createsheet()方法、setactivesheet()方法、getactivesheet()方法)
3、填充数据(setcellvalue()方法)
4、保存文件(phpexcel_iofactory::createwriter()方法、save方法)
二、phpexcel实现读取excel操作步骤
首先需要引入类文件,引入iofactory.php文件。
1、实例化excel读取对象
2、加载excel文件(全部加载 、选择加载)
3、读取excel文件(全部读取、逐行读取)
利用phpexcel实现excel文件的写入和读取代码:
<?php
$dir = dirname(__file__); //找出当前脚本所在路径
/*require $dir.'\lib\phpexcel_1.8.0_doc\classes\phpexcel.php'; //添加读取excel所需的类文件
$objphpexcel = new phpexcel(); //实例化一个phpexcel()对象
$objsheet = $objphpexcel->getactivesheet(); //选取当前的sheet对象
$objsheet->settitle('helen'); //对当前sheet对象命名
//常规方式:利用setcellvalue()填充数据
$objsheet->setcellvalue("a1","张三")->setcellvalue("b1","李四"); //利用setcellvalues()填充数据
//取巧模式:利用fromarray()填充数据
$array = array(
array("","b1","张三"),
array("","b2","李四")
);
$objsheet->fromarray($array); //利用fromarray()直接一次性填充数据
$objwriter = phpexcel_iofactory::createwriter($objphpexcel,'excel2007'); //设定写入excel的类型
$objwriter->save($dir.'/test.xlsx');*/ //保存文件
//利用php读取excel数据
require $dir.'\lib\phpexcel_1.8.0_doc\classes\phpexcel\iofactory.php';
$filename = $dir.'\test.xlsx';
$objphpexcelreader = phpexcel_iofactory::load($filename); //加载excel文件
foreach($objphpexcelreader->getworksheetiterator() as $sheet) //循环读取sheet
{
foreach($sheet->getrowiterator() as $row) //逐行处理
{
if($row->getrowindex()<2) //确定从哪一行开始读取
{
continue;
}
foreach($row->getcelliterator() as $cell) //逐列读取
{
$data = $cell->getvalue(); //获取cell中数据
echo $data;
}
echo '<br/>';
}
}
?>
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持脚本之家
申明:本教程内容由威凡网编辑整理并提供IT程序员分享学习,如文中有侵权行为,请与站长联系(QQ:254677821)!