Home >Backend Development >PHP Tutorial >Examples of phpexcel generating and reading excel files

Examples of phpexcel generating and reading excel files

WBOY
WBOYOriginal
2016-07-25 08:53:02914browse
  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 <= $highestrow; ++$row) {
  13. for ($col = 0; $col <= $highestcolumnindex; ++$col) {
  14. $exceldata[$row][] = $objworksheet->getcellbycolumnandrow($col, $row)->getvalue();
  15. }
  16. }
  17. return $exceldata;
  18. }
复制代码


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn