在php中導出excel有一種最簡單的方法就是導出csv文件,但要做到真正的導出excel文件我們可以借助於PHPExcel插件來實現。
PHPExcel是個很強大的PHP操作Excel的類庫,但是對於簡單的將數據用PHP 導出 Excel來說這有點顯得復雜,在google code上有一個PHP 導出 Excel的類,可以簡單調用,很方便。
代碼如下 復制代碼<?php
// load library
require 'php-excel.class.php';
// create a simple 2-dimensional array
$data = array(
1 => array ('Name', 'Surname'),
array('Schwarz', 'Oliver'),
array('Test', 'Peter')
);
// generate file (constructor parameters are optional)
$xls = new Excel_XML('UTF-8', false, 'My Test Sheet');
$xls->addArray($data);
$xls->generateXML('my-test');
?>
例2
代碼如下 復制代碼<?php
/**
* PHPEXCEL生成excel文件
* @author:firmy
* @desc 支持任意行列數據生成excel文件,暫未添加單元格樣式和對齊
*/
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(empty($data) || !is_array($data)){
die("data must be a array");
}
if(empty($fileName)){
exit;
}
$date = date("Y_m_d",time());
$fileName .= "_{$date}.xlsx";
//創建新的PHPExcel對象
$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');
//設置活動單指數到第一個表,所以Excel打開這是第一個表
$objPHPExcel->setActiveSheetIndex(0);
//將輸出重定向到一個客戶端web浏覽器(Excel2007)
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(!empty($_GET['excel'])){
$objWriter->save('php://output'); //文件通過浏覽器下載
}else{
$objWriter->save($fileName); //腳本方式運行,保存在當前目錄
}
exit;
}
phpexcel類的下載地址:http://php-excel.googlecode.com/files/php-excel-v1.1-20090910.zip