在php中导出excel有一种最简单的方法就是导出csv文件,但要做到真正的导出excel文件我们可以借助于PHPExcel插件来实现.
PHPExcel是个很强大的PHP操作Excel的类库,但是对于简单的将数据用PHP 导出 Excel来说这有点显得复杂,在google code上有一个PHP 导出 Excel的类,可以简单调用,很方便.
PHP中利用PHPExcel导出Excel示例代码如下:
- <?php
-
- require 'php-excel.class.php';
-
- $data = array(
- 1 => array ('Name', 'Surname'),
- array('Schwarz', 'Oliver'),
- array('Test', 'Peter')
- );
-
- $xls = new Excel_XML('UTF-8', false, 'My Test Sheet');
- $xls->addArray($data);
- $xls->generateXML('my-test');
- ?>
例2,代码如下:
- <?php
-
-
-
-
-
-
- require_once 'library/PHPExcel.php';
- require_once 'library/PHPExcel/Reader/Excel2007.php';
- require_once 'library/PHPExcel/Reader/Excel5.php';
- include_once 'library/PHPExcel/IOFactory.php';
-
- $fileName = "test_excel";
- $headArr = array("第一列","第二列","第三列");
- $data = array(array(1,2),array(1,3),array(5,7));
- getExcel($fileName,$headArr,$data);
-
-
- function getExcel($fileName,$headArr,$data){
- if(emptyempty($data) || !is_array($data)){
- die("data must be a array");
- }
- if(emptyempty($fileName)){
- exit;
- }
- $date = date("Y_m_d",time());
- $fileName .= "_{$date}.xlsx";
-
-
- $objPHPExcel = new PHPExcel();
- $objProps = $objPHPExcel->getProperties();
-
-
- $key = ord("A");
- foreach($headArr as $v){
- $colum = chr($key);
- $objPHPExcel->setActiveSheetIndex(0) ->setCellValue($colum.'1', $v);
- $key += 1;
- }
-
- $column = 2;
- $objActSheet = $objPHPExcel->getActiveSheet();
- foreach($data as $key => $rows){
- $span = ord("A");
- foreach($rows as $keyName=>$value){
- $j = chr($span);
- $objActSheet->setCellValue($j.$column, $value);
- $span++;
- }
- $column++;
- }
-
- $fileName = iconv("utf-8", "gb2312", $fileName);
-
- $objPHPExcel->getActiveSheet()->setTitle('Simple');
-
- $objPHPExcel->setActiveSheetIndex(0);
-
- header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
- header("Content-Disposition: attachment; filename="$fileName"");
- header('Cache-Control: max-age=0');
- $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
- if(!emptyempty($_GET['excel'])){
- $objWriter->save('php://output'); //文件通过浏览器下载
- }else{
- $objWriter->save($fileName);
- }
- exit;
-
- }
- ?>
phpexcel类的下载地址:http://php-excel.googlecode.com/files/php-excel-v1.1-20090910.zip |