php处理excel步骤介绍
遇到问题
平时在工作中,时常会出现将数据库表导出为excel或者将excel导入数据库表的需求。这一需求早早就已经实现过了,为了方便导入导出,兄弟连www.lampbrother.net将其分装成了两个方法作为记录。
代码实现
phpexcel类库的引用
phpexcel拥有强大的excel处理能力,在packagist上已经拥有数百万次的下载量,不过实话实说,excel的处理速度仍然是非常慢,数据量较大时慎重使用。在packagist上下载或者直接用composer require phpoffice/phpexcel之后,便可以使用phpexcel了。
导出成为excel
在绝大多数情况下,导出excel其实就是将二位数组转化为表格。
use namespace phpexcel;
/**
* @param $name string 要保存的excel的名字
* @param $ret_data 转换为表格的二维数组
* @throws phpexcel_exception
* @throws phpexcel_reader_exception
*/
function exportexcel($name, $ret_data){
$objphpexcel = new phpexcel();
//设置表格
$objphpexcel->getproperties()->setcreator($name)
->setlastmodifiedby($name)
->settitle("office 2007 xlsx test document")
->setsubject("office 2007 xlsx test document")
->setdescription("test document for office 2007 xlsx, generated using php classes.")
->setkeywords("office 2007 openxml php")
->setcategory("test result file");
//填充数据
foreach ($ret_data as $key => $row) {
$num = $key + 1;
//$row = array_values($row);
$i=0;
foreach ($row as $key2 => $value2) {
$objphpexcel->setactivesheetindex(0)->setcellvalue( cell::stringfromcolumnindex($i). ($num), $value2);
$i++;
}
}
//设置表格并输出
$objphpexcel->getactivesheet()->settitle($name);
header('content-type: application/vnd.ms-excel');
header("content-disposition: attachment;filename={$name}.xls");
header('cache-control: max-age=0');
header('cache-control: max-age=1');
header('last-modified: ' . gmdate('d, d m y h:i:s') . ' gmt');
header('cache-control: cache, must-revalidate');
header('pragma: public'); // http/1.0
$objwriter = phpexcel_iofactory::createwriter($objphpexcel, 'excel5');
$objwriter->save('php://output');
exit;
}
导入excel
同理,导入excel其实就是将excel的数据转化成为二维数组,这就要求excel必须符合格式。
function getrows($inputfilename)
{
if (!file_exists($inputfilename)) {
throw new exception("file not existed");
}
$inputfiletype = phpexcel_iofactory::identify($inputfilename);
$objreader = phpexcel_iofactory::createreader($inputfiletype);
$objphpexcel = $objreader->load($inputfilename);
$objworksheet = $objphpexcel->getactivesheet();
$highestrow = $objworksheet->gethighestrow();
$highestcolumn = $objworksheet->gethighestcolumn();
$highestcolumnindex = phpexcel_cell::columnindexfromstring($highestcolumn);//总列数
$row = 1;
$curr = array();
while ($row for ($col = 0; $col $value = str_replace(array("\n", "\n\r", "\r"), "", $objworksheet->getcellbycolumnandrow($col, $row)->getvalue());
$curr[$row][] = $value;
}
$row++;
}
array_shift($curr);//第一行一般是字段名(excel中列的标题),导入时要移除
return $curr;
}
其他
导出时保存的格式是xlsx,想要改成其他格式需要传入不同的参数。
导入时如果有多个sheet时需要在上次打开时在要导入的sheet页(以保证当前sheet为activesheet)关闭,或者根据sheet名在程序中选择sheet。
全网最新最细最实用WPS零基础入门到精通全套教程!带你真正掌握WPS办公! 内含Excel基础操作、函数设计、数据透视表等
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号