欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

phpexcel生成与读取excel文件的例子

程序员文章站 2022-05-25 15:13:38
...
  1. require_once 'classes/phpexcel/reader/excel2007.php';
  2. require_once 'classes/phpexcel/reader/excel5.php';
  3. include 'classes/phpexcel/iofactory.php';
  4. function arraytoexcel($data){
  5. $objphpexcel = new phpexcel();
  6. $objphpexcel->setactivesheetindex(0);
  7. $objphpexcel->getactivesheet()->settitle('firstsheet');
  8. $objphpexcel->getdefaultstyle()->getfont()->setname('arial');
  9. $objphpexcel->getdefaultstyle()->getfont()->setsize(10);
  10. //add data
  11. $i = 2;
  12. foreach ($data as $line){
  13. $objphpexcel->getactivesheet()->setcellvalue('a'.$i, $line['from']);
  14. $objphpexcel->getactivesheet()->getcell('a'.$i)->setdatatype('n');
  15. $objphpexcel->getactivesheet()->setcellvalue('b'.$i, $line['to']);
  16. $objphpexcel->getactivesheet()->getcell('b'.$i)->setdatatype('n');
  17. $i++;
  18. }
  19. $objwriter = phpexcel_iofactory::createwriter($objphpexcel, 'excel5');
  20. $file = 'excel.xls';
  21. $objwriter->save($file);
  22. }
复制代码

>>> 更多php教程内容,请关注本站php编程栏目。

如果不希望保存在服务器上,希望生成以后直接下载到客户端,可以在输出文件时添加以下代码,而不使用 $objwriter->save($file);

  1. header("pragma: public");
  2. header("expires: 0");
  3. header("cache-control:must-revalidate, post-check=0, pre-check=0");
  4. header("content-type:application/force-download");
  5. header("content-type:application/vnd.ms-execl");
  6. header("content-type:application/octet-stream");
  7. header("content-type:application/download");
  8. header('content-disposition:attachment;filename="excel.xls"');
  9. header("content-transfer-encoding:binary");
  10. $objwriter->save('php://output');
复制代码

下面来看一个读取excel文件内容的实例: 以下代码函数exceltoarray的功能是把一个excel里的内容重新整理放到一个数组了。

  1. require_once 'classes/phpexcel.php';
  2. require_once 'classes/phpexcel/iofactory.php';
  3. function exceltoarray($file){
  4. $objreader = phpexcel_iofactory::createreader('excel5');
  5. $objreader->setreaddataonly(true);
  6. $objphpexcel = $objreader->load($file);
  7. $objworksheet = $objphpexcel->getactivesheet();
  8. $highestrow = $objworksheet->gethighestrow();
  9. $highestcolumn = $objworksheet->gethighestcolumn();
  10. $highestcolumnindex = phpexcel_cell::columnindexfromstring($highestcolumn);
  11. $exceldata = array();
  12. for ($row = 2; $row for ($col = 0; $col $exceldata[$row][] = $objworksheet->getcellbycolumnandrow($col, $row)->getvalue();
  13. }
  14. }
  15. return $exceldata;
  16. }
复制代码