今天主要研究数据加入EXCEL并导出的问题,先不从数据库提取数据导出,自己先写一个二维数组,然后遍历二维数组写入excel模板中导出,首先根据模板excel的内容书写对应的二维数组
$arr=array(array("111-3004394-8497032","UMN207-05MM","UMN207-05MM","2","Eric S Herbert / Entergy","600 Rockyhill Rd","PNPS"," ","plymouth","ma","02360","US","508 830-8823","","","","","","","1",""),
array("112-3297805-3545827","UMN207-05MM","UMN207-05MM","1","Yibai Liao","11 BANNISTER DR"," "," ","HOPEWELL JUNCTION"," ","12533-8204","US","9175926724","","","","","","","1",""));
然后用foreach遍历二维数组并写入模板excle文件具体代码如下
$row=2;
foreach ($arr as $order)
{
$col=0;
foreach($order as $val)
$objPHPExcel->setActiveSheetIndex()->setCellValueByColumnAndRow($col, $row, $val);
$col++;
}
$row++;
}
$row为行,指定从第二行插入数据,并且循环换行, $val为二维数组数据,$col为列,基本实现数据写入excel表格并导出,整体代码如下:
<?php
if($_POST['eub']==1)
{
header("location:ListOrders.php?t=OrderStatus&fc=all&orderstatus=Unshipped&range=14&submit=Go");
}
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
date_default_timezone_set('Europe/London');
if (PHP_SAPI == 'cli')
die('This example should only be run from a Web Browser');
/** Include PHPExcel */
require_once dirname(__FILE__) . '/../plugins/PHPExcel-1.8/Classes/PHPExcel.php';
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
// Read from Excel2007 (.xlsx) template
//echo date('H:i:s') , " Load Excel5 template file" , EOL;
$objReader = PHPExcel_IOFactory::createReader('Excel5');
$objPHPExcel = $objReader->load("../template/eub.xls");
//print_r($objPHPExcel);
//die();
$filename = "eub-".date("YmdHis").".xls";
$row = 2;
// Add some data
$arr=array(array("111-3004394-8497032","UMN207-05MM","UMN207-05MM","2","Eric S Herbert / Entergy","600 Rockyhill Rd","PNPS"," ","plymouth","ma","02360","US","508 830-8823","","","","","","","1",""),
array("112-3297805-3545827","UMN207-05MM","UMN207-05MM","1","Yibai Liao","11 BANNISTER DR"," "," ","HOPEWELL JUNCTION"," ","12533-8204","US","9175926724","","","","","","","1",""));
foreach ($OrderList as $order)
{
$col=0;
foreach($order as $val)
$objPHPExcel->setActiveSheetIndex()->setCellValueByColumnAndRow($col, $row, $val);
$col++;
}
$row++;
}
// Redirect output to a client’s web browser (Excel2007)
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset="GB2312"');
header('Content-Disposition: attachment;filename="'.$filename.'"');
header('Cache-Control: max-age=0');
// If you're serving to IE 9, then the following may be needed
header('Cache-Control: max-age=1');
// If you're serving to IE over SSL, then the following may be needed
header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
header ('Pragma: public'); // HTTP/1.0
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
exit;
?>
下一步就是从数据库读取数据写入excel模板表并导出的实现过程。