Table of Contents
1. 安装PHPExcel到Codeigniter
2. 安装完毕,写一个导出excel的控制器(Controller)
注意事项:阅读方式excel方式不能指定死,让他自动识别文件来自动读取。
3. 读取excel详细资料
 
1.  创建一个ExcelReader去加载一个Excel文档
2.1.ReadingOnly Data from a Spreadsheet File
详细资料:http://blog.csdn.net/andy1219111/article/details/7673796;
Home Backend Development PHP Tutorial Codeigniter(CI)结合PHPExcel类完成数据导入

Codeigniter(CI)结合PHPExcel类完成数据导入

Jun 20, 2016 pm 12:33 PM


1. 安装PHPExcel到Codeigniter

1) 解压压缩包里的Classes文件夹中的内容到application\libraries\目录下,目录结构如下:

– application\libraries\PHPExcel.php

– application\libraries\PHPExcel (文件夹)

2)修改application\libraries\PHPExcel\IOFactory.php 文件

– 将其类名从PHPExcel_IOFactory改为IOFactory,遵从CI类命名规则。

– 将其构造函数改为public(__construct)


2. 安装完毕,写一个导出excel的控制器(Controller)

    public function index(){


            //判断上传文件存在值

            if(!empty($_FILES)){

                $filename = $_FILES['file']['name'];//被上传文件的名称
                $filetype = $_FILES["file"]["type"];//被上传文件的类型
                $filesize = $_FILES["file"]["size"];// 被上传文件的大小,以字节计
                $filetmp = $_FILES["file"]["tmp_name"];//存储在服务器的文件的临时副本的名称
                $fileerror = $_FILES["file"]["error"];//由文件上传导致的错误代码


                //判断是否上传成功
                if($fileerror==0){
                    //判断是否是excel表格
                    if($filetype=="application/vnd.ms-excel" || $filetype=="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"){

                        /*设置保存路径*/
                        $filePath = 'uploads/excel/';
                        $str = "";   
                          
                        /*加载PHPExcel*/
                        $this->load->library('PHPExcel.php');
                        $this->load->library('PHPExcel/IOFactory.php');
                        //$this->load->library('PHPExcel/Reader/Excel5.php');

                         //注意设置时区
                        $time=date("YmdHis");//去当前上传的时间
                        //获取上传文件的扩展名
                        $extend=strrchr ($filename,'.');
                        //上传后的文件名
                        $name=$time.$extend;
                        //上传后的文件名地址
                        $uploadfile=$filePath.$name;//上传后的文件名地址
                        
                        //move_uploaded_file() 函数将上传的文件移动到新位置。若成功,则返回 true,否则返回 false。
                        $result=move_uploaded_file($filetmp,$uploadfile);//假如上传到当前目录下
                        


                        //echo $result;
                        //如果上传文件成功,就执行导入excel操作

                       if($result){

                               $inputFileType = IOFactory::identify($uploadfile);//确定输入文件的格式
                            $objReader = IOFactory::createReader($inputFileType);//穿件相对应的阅读器
                            $objPHPExcel = $objReader->load($uploadfile);          //加载要读取的文件
                            $sheet = $objPHPExcel->getSheet();                    //得到当前活动sheet
                            $highestRow = $sheet->getHighestRow();           //取得总行数
                            $highestColumn = $sheet->getHighestColumn(); //取得总列数
                           // print_r($highestRow);
                            //print_r($highestColumn);
                            /* 第一种方法

                            //循环读取excel文件,读取一条,插入一条
                            for($j=1;$j                             {
                                for($k='A';$k                                 {
                                    //
                                    //这种方法简单,但有不妥,以'\\'合并为数组,再分割\\为字段值插入到数据库
                                    //实测在excel中,如果某单元格的值包含了\\导入的数据会为空        
                                    //
                                    $str .=$objPHPExcel->getActiveSheet()->getCell("$k$j")->getValue().'\\';//读取单元格
                                }
                                //echo $str; die();
                                //explode:函数把字符串分割为数组。
                                $strs = explode("\\",$str);
                                print_r($strs);
                                $sql = "INSERT INTO te(`id`, `name`) VALUES (
                                '{$strs[0]}',
                                '{$strs[1]}')";
                                //die($sql);

                                if(!mysql_query($sql))
                                {
                                    return false;
                                    echo 'sql语句有误';
                                }
                                mysql_query($sql);
                                $str = "";
                            }
                            unlink($uploadfile); //删除上传的excel文件
                            $msg = "导入成功!";
                            */

                            /* 第二种方法*/
                            $objWorksheet = $objPHPExcel->getActiveSheet();
                            $highestRow = $objWorksheet->getHighestRow();
                            
                            $highestColumn = $objWorksheet->getHighestColumn();
                            $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);//总列数
                            
                            $headtitle=array();  
                            for ($row = 2;$row
                                $arr=array();
                                //注意highestColumnIndex的列数索引从0开始
                                for ($col = 0;$col

                                        $arr[$col] =$objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
                                }
                                

                                // $sql = "INSERT INTO admins(`account`, `pwd`, `username`, `power`, `tel`,`sex`,`work_numjob`,`job`,`sector`) VALUES (
                                // '{$strs[0]}',
                                // '{$strs[1]}',
                                // '{$strs[2]}',
                                // '{$strs[3]}',
                                // '{$strs[4]}',
                                // '{$strs[5]}',
                                // '{$strs[6]}',
                                // '{$strs[7]}',
                                // '{$strs[8]}',)";

                                $data=array(
                                            'account'=>$arr['0'],
                                            'pwd'=>$arr['1'],
                                            'username'=>$arr['2'],
                                            'power'=>$arr['3'],
                                            'tel'=>$arr['4'],
                                            'sex'=>$arr['5'],
                                            'work_num'=>$arr['6'],
                                            'job'=>$arr['7'],
                                            'sector'=>$arr['8'],

                                        );

                                $this->db->insert("admins",$data);

                            }
                            unlink($uploadfile);
                            show_msg("导入成功",site_url("链接地址"));//跳转地址
                             //删除上传的excel文件

                    }

                    }else{

                        show_msg("上传文件非cvs格式,请重新上传");
                    }


                }else{

                    switch ($fileerror){
                            case 1:
                             show_msg("上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值.");
                              break;
                            case 2:
                              show_msg("上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值");
                              break;
                            case 3:
                             show_msg("文件只有部分被上传");
                              break;
                            case 4:
                                show_msg("没有文件被上传");
                              break;
                    }


                }

            }

    }

注意事项:阅读方式excel方式不能指定死,让他自动识别文件来自动读取。

3. 读取excel详细资料


1.      导入一个Excel最简单的方法是使用PHPExel的IO Factory,调用PHPExcel_IOFactory类的静态法load,它可以自动识别文档格式,包括Excel2007、 Excel2003XML、OOCalcSYLK、Gnumeric、CSV。返回一个PHPExcel的实例。

 

//加载工厂类

include'PHPExcel/IOFactory.php';
//要读取的xls文件路径

$inputFileName = './sampleData/example1.xls';

/** 用PHPExcel_IOFactory的load方法得到excel操作对象  **/
$objPHPExcel = PHPExcel_IOFactory::load($inputFileName);

//得到当前活动表格,调用toArray方法,得到表格的二维数组

$sheetData =$objPHPExcel->getActiveSheet()->toArray(null,true,true,true);

var_dump($sheetData);

 

1.  创建一个ExcelReader去加载一个Excel文档

如果你知道这个Excel文档的格式,可以建立一个相应的Reader去加载要读取的Excel文档。但是如果你加载了错误的文档类型,可会产生不可预知的错误。

 

 

$inputFileName = './sampleData/example1.xls';

/** Create a new Excel5 Reader  **/
$objReader = new PHPExcel_Reader_Excel5();
//    $objReader = new PHPExcel_Reader_Excel2007();
//    $objReader = new PHPExcel_Reader_Excel2003XML();
//    $objReader = new PHPExcel_Reader_OOCalc();
//    $objReader = new PHPExcel_Reader_SYLK();
//    $objReader = new PHPExcel_Reader_Gnumeric();
//    $objReader = new PHPExcel_Reader_CSV();
/** Load $inputFileName to a PHPExcel Object  **/
$objPHPExcel = $objReader->load($inputFileName);

//得到当前活动sheet

$curSheet =$objPHPExcel->getActiveSheet();

//以二维数组形式返回该表格的数据

$sheetData = $curSheet->toArray(null,true,true,true);

var_dump($sheetData);

 

也可以用PHPExcel_IOFactory的createReader方法去得到一个Reader对象,无需知道要读取文件的格式。

 

 

$inputFileType = 'Excel5';
//    $inputFileType = 'Excel2007';
//    $inputFileType = 'Excel2003XML';
//    $inputFileType = 'OOCalc';
//    $inputFileType = 'SYLK';
//    $inputFileType = 'Gnumeric';
//    $inputFileType = 'CSV';
$inputFileName = './sampleData/example1.xls';

/**  Create a new Reader of the type defined in $inputFileType  **/
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
/**  Load $inputFileName to a PHPExcel Object  **/
$objPHPExcel = $objReader->load($inputFileName);

//得到当前活动sheet

$curSheet = $objPHPExcel->getActiveSheet();

//以二维数组形式返回该表格的数据

$sheetData = $curSheet->toArray(null,true,true,true);

var_dump($sheetData);

如果在读取文件之前,文件格式未知,你可以通过IOFactory 的 identify()方法得到文件类型,然后通过createReader()方法去穿件阅读器。

$inputFileName = './sampleData/example1.xls';

/**  确定输入文件的格式  **/
$inputFileType = PHPExcel_IOFactory::identify($inputFileName);
/** 穿件相对应的阅读器  **/
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
/**  加载要读取的文件  **/
$objPHPExcel = $objReader->load($inputFileName);

2.  设置Excel的读取选项

在使用load()方法加载文件之前,可以设置读取选项来控制load的行为.

2.1.ReadingOnly Data from a Spreadsheet File

setReadDataOnly()方法,配置阅读器不关注表格数据的数据类型,都以string格式返回


$inputFileType = 'Excel5';
$inputFileName = './sampleData/example1.xls';

/**  Create a new Reader of the type defined in $inputFileType  **/
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
/**  配置单元格数据都以字符串返回  **/
$objReader->setReadDataOnly(true);
/**  Load $inputFileName to a PHPExcel Object  **/
$objPHPExcel = $objReader->load($inputFileName);

$sheetData =$objPHPExcel->getActiveSheet()->toArray(null,true,true,true);

var_dump($sheetData);


详细资料:http://blog.csdn.net/andy1219111/article/details/7673796;



Statement of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

11 Best PHP URL Shortener Scripts (Free and Premium) 11 Best PHP URL Shortener Scripts (Free and Premium) Mar 03, 2025 am 10:49 AM

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Introduction to the Instagram API Introduction to the Instagram API Mar 02, 2025 am 09:32 AM

Following its high-profile acquisition by Facebook in 2012, Instagram adopted two sets of APIs for third-party use. These are the Instagram Graph API and the Instagram Basic Display API.As a developer building an app that requires information from a

Working with Flash Session Data in Laravel Working with Flash Session Data in Laravel Mar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

Build a React App With a Laravel Back End: Part 2, React Build a React App With a Laravel Back End: Part 2, React Mar 04, 2025 am 09:33 AM

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Simplified HTTP Response Mocking in Laravel Tests Simplified HTTP Response Mocking in Laravel Tests Mar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

cURL in PHP: How to Use the PHP cURL Extension in REST APIs cURL in PHP: How to Use the PHP cURL Extension in REST APIs Mar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

12 Best PHP Chat Scripts on CodeCanyon 12 Best PHP Chat Scripts on CodeCanyon Mar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Announcement of 2025 PHP Situation Survey Announcement of 2025 PHP Situation Survey Mar 03, 2025 pm 04:20 PM

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

See all articles