1、下载phpexcel,将压缩包中的classes复制到protected/extensions下并修改为PHPExcel。
2、修改YII配置文件config/main.php
[php] view plaincopy
- ‘import‘=>array(
- ‘application.extensions.PHPExcel.PHPExcel‘,
- ),
(以下处理PHPExcel autoload和YII autoload相冲突的方法任选其一,推荐第4种,最符合YII标准)
3.1、修改PHPExcel中的Autoloader.php
[php] view plaincopy
- PHPExcel_Autoloader::Register();
- PHPExcel_Shared_ZipStreamWrapper::register();
修改为
[php] view plaincopy
- Yii::registerAutoloader(array(‘PHPExcel_Autoloader‘,‘Register‘),true);
3.2、按照下面的代码修改PHPExcel代码目录里的Autoloader.php文件
[php] view plaincopy
- public static function Register() {
- /*
- if (function_exists(‘__autoload‘)) {
- //Register any existing autoloader function with SPL, so we don‘t get any clashes
- spl_autoload_register(‘__autoload‘);
- }
- //Register ourselves with SPL
- return spl_autoload_register(array(‘PHPExcel_Autoloader‘, ‘Load‘));
- */
- $functions = spl_autoload_functions();
- foreach ( $functions as $function)
- spl_autoload_unregister($function);
- $functions = array_merge(array(array(‘PHPExcel_Autoloader‘,‘Load‘)),$functions);
- foreach ( $functions as $function)
- $x = spl_autoload_register($function);
- return $x;
- } // function Register()
3.3、在需要使用PHPExcel时使用以下代码
[php] view plaincopy
- $filePath = ‘/home/public_html/sqt/protected/data/queueSql/company.xls‘;
- spl_autoload_unregister(array(‘YiiBase‘, ‘autoload‘));
- $phpExcelPath = Yii::getPathOfAlias(‘application.extensions.PHPExcel.PHPExcel‘);
- include($phpExcelPath . DIRECTORY_SEPARATOR . ‘IOFactory.php‘);
- spl_autoload_register(array(‘YiiBase‘, ‘autoload‘));
- $PHPExcel = PHPExcel_IOFactory::load( $filePath);
3.4、只要设置Yii::$enableIncludePath为false,第三方类库就有了执行自己的autoload方法的机会,并且不需要配置config/main.php,非常方便灵活
[php] view plaincopy
- Yii::$enableIncludePath = false;
- Yii::import(‘application.extensions.PHPExcel.PHPExcel‘, 1);
-------------------------------------------------------------------------------
导入Excel文件方法
[php] view plaincopy
- public function actionLoad() {
- if(isset($_POST[‘submit‘])) {
- $file = CUploadedFile::getInstanceByName(‘file‘);//获取上传的文件实例
- if($file->getType() == ‘application/vnd.ms-excel‘) {
- $excelFile = $file->getTempName();//获取文件名
- //这里就是导入PHPExcel包了,要用的时候就加这么两句,方便吧
- Yii::$enableIncludePath = false;
- Yii::import(‘application.extensions.PHPExcel.PHPExcel‘, 1);
- $phpexcel = new PHPExcel;
- $excelReader = PHPExcel_IOFactory::createReader(‘Excel5‘);
- $phpexcel = $excelReader->load($excelFile)->getSheet(0);//载入文件并获取第一个sheet
- $total_line = $phpexcel->getHighestRow();
- $total_column = $phpexcel->getHighestColumn();
- for ($row = 2; $row <= $total_line; $row++) {
- $data = array();
- for ($column = ‘A‘; $column <= $total_column; $column++) {
- $data[] = trim($phpexcel->getCell($column.$row) -> getValue());
- }
- }
- }
- }
- }
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-26 13:52:40