-
- require_once 'classes/phpexcel/reader/excel2007.php';
- require_once 'classes/phpexcel/reader/excel5.php';
- include 'classes/phpexcel/iofactory.php';
-
- function arraytoexcel($data){
- $objphpexcel = new phpexcel();
- $objphpexcel->setactivesheetindex(0);
- $objphpexcel->getactivesheet()->settitle('firstsheet');
- $objphpexcel->getdefaultstyle()->getfont()->setname('arial');
- $objphpexcel->getdefaultstyle()->getfont()->setsize(10);
- //add data
-
- $i = 2;
- foreach ($data as $line){
- $objphpexcel->getactivesheet()->setcellvalue('a'.$i, $line['from']);
- $objphpexcel->getactivesheet()->getcell('a'.$i)->setdatatype('n');
- $objphpexcel->getactivesheet()->setcellvalue('b'.$i, $line['to']);
- $objphpexcel->getactivesheet()->getcell('b'.$i)->setdatatype('n');
- $i ;
- }
- $objwriter = phpexcel_iofactory::createwriter($objphpexcel, 'excel5');
- $file = 'excel.xls';
- $objwriter->save($file);
- }
复制代码
>>> 更多php教程内容,请关注本站php编程栏目。
如果不希望保存在服务器上,希望生成以后直接下载到客户端,可以在输出文件时添加以下代码,而不使用 $objwriter->save($file);
-
- header("pragma: public");
- header("expires: 0");
- header("cache-control:must-revalidate, post-check=0, pre-check=0");
- header("content-type:application/force-download");
- header("content-type:application/vnd.ms-execl");
- header("content-type:application/octet-stream");
- header("content-type:application/download");
- header('content-disposition:attachment;filename="excel.xls"');
- header("content-transfer-encoding:binary");
- $objwriter->save('php://output');
复制代码
下面来看一个读取excel文件内容的实例:
以下代码函数exceltoarray的功能是把一个excel里的内容重新整理放到一个数组了。
-
- require_once 'classes/phpexcel.php';
- require_once 'classes/phpexcel/iofactory.php';
- function exceltoarray($file){
- $objreader = phpexcel_iofactory::createreader('excel5');
- $objreader->setreaddataonly(true);
- $objphpexcel = $objreader->load($file);
- $objworksheet = $objphpexcel->getactivesheet();
- $highestrow = $objworksheet->gethighestrow();
- $highestcolumn = $objworksheet->gethighestcolumn();
- $highestcolumnindex = phpexcel_cell::columnindexfromstring($highestcolumn);
- $exceldata = array();
- for ($row = 2; $row <= $highestrow; $row) {
- for ($col = 0; $col <= $highestcolumnindex; $col) {
- $exceldata[$row][] = $objworksheet->getcellbycolumnandrow($col, $row)->getvalue();
- }
- }
- return $exceldata;
- }
复制代码
|