如何将php网页中的数据导出为Excel文件?

时间:2019-03-07 11:10:01

标签: php excel

<?php
   include ('PHPExcel.php');
   include ('PHPExcel/IOFactory.php');
   include ('PHPExcel\Writer\Excel2007.php');
   $objPHPExcel = new PHPExcel();
	    
   $objPHPExcel->setActiveSheetIndex(0);
   $worksheet = $objPHPExcel->getActiveSheet();

   $worksheet->setCellValue('A1', 'User name');
   $worksheet->setCellValue('B1', 'First name');
   $worksheet->setCellValue('C1', 'Last name');
	    
   $excelRow = 2;
	    	
   $worksheet->setCellValue('A' . $excelRow, 'admin');
   $worksheet->setCellValue('B' . $excelRow, 'testuser');
   $worksheet->setCellValue('C' . $excelRow, 'testuser');

   header('Content-Type: application/vnd.ms-excel');
   header('Content-Disposition: attachment;filename=Test.xls');
   header('Cache-Control: max-age=0');	
   $objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
   $objWriter->save('php://output');
   exit;
?>

嗨,我想用php将数据导出为ex​​cel文件。我可以将文件下载为excel。但是我在Excel中出现如下错误。 您能帮我解决问题吗?预先谢谢你。

  

致命错误:未捕获PHPExcel_Writer_Exception:无法将临时zip文件C:\ Users ** \ AppData \ Local \ Temp \ php65EC.tmp复制到php:// output。在C:\ xampp \ htdocs \ xampp \ PhpTest \ PHPExcel \ Writer \ Excel2007.php:395

     

警告副本(C:\ Users ** \ AppData \ Local \ Temp \ php65EC.tmp):无法打开流:C:\ xampp \ htdocs \ xampp \ PhpTest \ PHPExcel \ Writer \中没有此类文件或目录Excel2007.php

1 个答案:

答案 0 :(得分:0)

我写了下面的代码,而不是“ $ objWriter-> save('php:// output');”。 excel正确打开了。

$filePath = sys_get_temp_dir() . "/" . rand(0, getrandmax()) . rand(0, getrandmax()) . ".tmp";
$objWriter->save($filePath);
readfile($filePath);
unlink($filePath);