yii集成phpexcel

public function actionOutExcel(){
			//echo  Yii::app()->request->baseUrl;
			$danju = OrderInfo::model()->findByPk($_GET['id']);
			
			ob_end_clean();
    		ob_start();
			
			/** PHPExcel */
			//Yii::import('application.vendors.*');
 			include_once(dirname(dirname(__FILE__)).'/extensions/PHPExcel.php');
			include_once(dirname(dirname(__FILE__)).'/extensions/PHPExcel/Writer/Excel2007.php');
			$objPHPExcel = new PHPExcel();
			
			$objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
										 ->setLastModifiedBy("Maarten Balliauw")
										 ->setTitle("Office 2007 XLSX Test Document")
										 ->setSubject("Office 2007 XLSX Test Document")
										 ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
										 ->setKeywords("office 2007 openxml php")
										 ->setCategory("Test result file");
			
			$objPHPExcel->setActiveSheetIndex(0)
			            ->setCellValue('A1', '商品编码')
			            ->setCellValue('B1', '商品名称')
			            ->setCellValue('C1', '商品规格')
			            ->setCellValue('D1', '盘点库存')
			            ->setCellValue('E1', '账面库存');

			$model =$this->loadModel($_GET['id']);
			if(!empty($model->Goods)){
				$i =2;
				foreach ($model->Goods as  $one){
					$guige = '';
					$guige = $one->StockSpliterValue;
					$objPHPExcel->setActiveSheetIndex(0)
			            ->setCellValue("A$i", $one->gd_sn)
			            ->setCellValue("B$i", $one->gd_name)
			            ->setCellValue("C$i", "$guige")
			            ->setCellValue("D$i", $one->order_num)
			            ->setCellValue("E$i", $one->stock_num);
				   $i++;		
				}
			}			
			$objPHPExcel->getActiveSheet()->setTitle('盘点单');
			$objPHPExcel->setActiveSheetIndex(0);
//			$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
//			$objWriter->save(str_replace('.php', '.xlsx', __FILE__));
			$objWriter = new PHPExcel_Writer_Excel5($objPHPExcel);
			
			header("Pragma: public");
			header("Expires: 0");
			//header('Content-Type: application/vnd.ms-excel;charset=utf8');
			header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
			header("Content-Type:application/force-download");
			header("Content-Type:application/vnd.ms-execl");
			header("Content-Type:application/octet-stream");
			header("Content-Type:application/download");
			$fireName = $danju->order_sn.'-盘点单';
			header("Content-Disposition:attachment;filename=$fireName.xls");
			header("Content-Transfer-Encoding:binary");
			$objWriter->save("php://output");

			Yii::app()->end();
			spl_autoload_register(array('YiiBase','autoload'));
	}


注意:在导出excel的时候,遇到经常乱码的问题,需要加上 

  1. ob_end_clean();  
  2.             ob_start();

posted @ 2012-03-13 16:24  夏至冬末  阅读(149)  评论(0编辑  收藏  举报