search
HomeBackend DevelopmentPHP TutorialPHPExcel(一)- 导出功能

PHPExcel(1)-- 导出功能
PHPExcel导出功能

Web开发的时候,经常会遇到需要将数据库中某些表单导出到excel文件中的问题。我在运用yii框架做web开发过程中,发现有个应用为PHPExcel,该应用能够实现excel文件的导入导出,刚好能够满足需要的要求。一下是自己应用 PHPExcel 做数据导出的记录。

1、首先下载该应用,github链接为:https://github.com/PHPOffice/PHPExcel

2、在 protected/extensions 路径下建立 PHPexcel 目录,将下载的 PHPExcel 文件解压。

3、将解压后的classes目录下所有内容,拷贝放到protected/extensions/PHPexcel 目录下

4、在控制器文件 XXX.Controller.php 中,先引入相关文件

<?phpYii::import (&#39;application.extensions.*&#39;);require_once(&#39;PHPExcel/PHPExcel.php&#39;);require_once &#39;PHPExcel/PHPExcel/Writer/Excel5.php&#39;; // 用于其他低版本xlsrequire_once &#39;PHPExcel/PHPExcel/Writer/Excel2007.php&#39;; // 用于 excel-2007 格式...


5、编写方法Download(以下是自己开发过程中的部分代码)
public function actionDownload($option)    {        // Create new PHPExcel object        $objPHPExcel = new PHPExcel();        // Set properties        $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->getActiveSheet()->mergeCells('A1:G1');        //$objPHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);        //$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setAutoSize(true);        //$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(20);        //$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(20);        $subjects = Subject::model()->findAll("headteacher=:name", array(":name" => Yii::app()->session['name'])); //找出相关课程组        foreach ($subjects as $item1) {            $criteria = new CDbCriteria; // 创建CDbCriteria对象            $criteria->addCondition("suid = :id");            $criteria->params[':id'] = $item1->id;            $criteria->select = '*';            //按照返回参数搜索选题信息            if ($option == 1) {                $criteria->order = 'Cid';                //$criteria -> limit = 3;                $b = Selectcourse::model()->findAll($criteria);                $objPHPExcel->setActiveSheetIndex(0)                    ->setCellValue('A1', '选题情况')                    ->setCellValue('A2', '学生ID')                    ->setCellValue('B2', '学生姓名')                    ->setCellValue('C2', '课程名称')                    ->setCellValue('D2', '题目名称')                    ->setCellValue('E2', '选题时间');                $count = 2;                foreach ($b as $item2) {                    $count += 1;                    $l1 = "A" . "$count";                    $l2 = "B" . "$count";                    $l3 = "C" . "$count";                    $l4 = "D" . "$count";                    $l5 = "E" . "$count";                    $objPHPExcel->setActiveSheetIndex(0)                        ->setCellValue($l1, $item2->sid)                        ->setCellValue($l2, Student::model()->find(array('condition' => 'id=' . $item2->sid,))->name)                        ->setCellValue($l3, $item1->name)                        ->setCellValue($l4, Course::model()->find(array('condition' => 'Cid=' . $item2->cid,))->Cname)                        ->setCellValue($l5, $item2->apply_time);                }            }            if ($option == 2) {                $criteria->order = 'sid';                //$criteria -> limit = 3;                $b = Selectcourse::model()->findAll($criteria);                $objPHPExcel->setActiveSheetIndex(0)                    ->setCellValue('A1', '选题情况')                    ->setCellValue('A2', '学生ID')                    ->setCellValue('B2', '学生姓名')                    ->setCellValue('C2', '课程名称')                    ->setCellValue('D2', '题目名称')                    ->setCellValue('E2', '选题时间');                $count = 2;                foreach ($b as $item2) {                    $count += 1;                    $l1 = "A" . "$count";                    $l2 = "B" . "$count";                    $l3 = "C" . "$count";                    $l4 = "D" . "$count";                    $l5 = "E" . "$count";                    $objPHPExcel->setActiveSheetIndex(0)                        ->setCellValue($l1, $item2->sid)                        ->setCellValue($l2, Student::model()->find(array('condition' => 'id=' . $item2->sid,))->name)                        ->setCellValue($l3, $item1->name)                        ->setCellValue($l4, Course::model()->find(array('condition' => 'Cid=' . $item2->cid,))->Cname)                        ->setCellValue($l5, $item2->apply_time);                }            }        }        // Rename sheet        $objPHPExcel->getActiveSheet()->setTitle('学生选题信息');        // Set active sheet index to the first sheet, so Excel opens this as the first sheet        $objPHPExcel->setActiveSheetIndex(0);        // Redirect output to a client’s web browser (Excel5)        header('Content-Type: application/vnd.ms-excel');        header('Content-Disposition: attachment;filename="学生选题信息.xls"');        header('Cache-Control: max-age=0');        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');        $objWriter->save('php://output');    }



6、不要忘了在用户访问控制里面添加动作download
public function accessRules(){array('allow', // allow admin user to perform 'admin' and 'delete' actions                'actions' => array('download'),                'roles' => array('...'),            ),}



7、在对应的view文件中,编写链接
<?php echo CHtml::link(CHtml::encode("》导出Excel表格"), array(&#39;download&#39;,&#39;option&#39; => $option)); ?>



8、完成将数据以excel文件导出。


以上是自己对PHPExcel的一个应用,因为是初次接触,用的也不熟练,难免有一些不当,望大家指出,共同进步!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.