Table of Contents
导入Excel表:
Home Backend Development PHP Tutorial 利用phpExcel实现Excel数据的导入导出(全步骤详细解析)_php技巧

利用phpExcel实现Excel数据的导入导出(全步骤详细解析)_php技巧

May 17, 2016 am 08:52 AM
excel import and export

很多文章都有提到关于使用phpExcel实现Excel数据的导入导出,大部分文章都差不多,或者就是转载的,都会出现一些问题,下面是本人研究phpExcel的使用例程总结出来的使用方法,接下来直接进入正题。

首先先说一下,本人的这段例程是使用在Thinkphp的开发框架上,要是使用在其他框架也是同样的方法,很多人可能不能正确的实现Excel的导入导出,问题基本上都是phpExcel的核心类引用路径出错,如果有问题大家务必要对路劲是否引用正确进行测试。

(一)导入Excel

第一,在前台html页面进行上传文件:如:

复制代码 代码如下:


        

导入Excel表:

          



第二,在对应的php文件进行文件的处理
复制代码 代码如下:

 if (! empty ( $_FILES ['file_stu'] ['name'] ))

 {
    $tmp_file = $_FILES ['file_stu'] ['tmp_name'];
    $file_types = explode ( ".", $_FILES ['file_stu'] ['name'] );
    $file_type = $file_types [count ( $file_types ) - 1];

     /*判别是不是.xls文件,判别是不是excel文件*/
     if (strtolower ( $file_type ) != "xls")             
    {
          $this->error ( '不是Excel文件,重新上传' );
     }

    /*设置上传路径*/
     $savePath = SITE_PATH . '/public/upfile/Excel/';

    /*以时间来命名上传的文件*/
     $str = date ( 'Ymdhis' );
     $file_name = $str . "." . $file_type;

     /*是否上传成功*/
     if (! copy ( $tmp_file, $savePath . $file_name ))
      {
          $this->error ( '上传失败' );
      }

    /*

       *对上传的Excel数据进行处理生成编程数据,这个函数会在下面第三步的ExcelToArray类中

      注意:这里调用执行了第三步类里面的read函数,把Excel转化为数组并返回给$res,再进行数据库写入

    */
  $res = Service ( 'ExcelToArray' )->read ( $savePath . $file_name );

   /*

        重要代码 解决Thinkphp M、D方法不能调用的问题  

        如果在thinkphp中遇到M 、D方法失效时就加入下面一句代码

    */
   //spl_autoload_register ( array ('Think', 'autoload' ) );

   /*对生成的数组进行数据库的写入*/
   foreach ( $res as $k => $v )
   {
       if ($k != 0)
      {
           $data ['uid'] = $v [0];
           $data ['password'] = sha1 ( '111111' );
           $data ['email'] = $v [1];

           $data ['uname'] = $v [3];

          $data ['institute'] = $v [4];
         $result = M ( 'user' )->add ( $data );
         if (! $result)
         {
              $this->error ( '导入数据库失败' );
          }
      }
   }

}


第三:ExcelToArrary类,用来引用phpExcel并处理Excel数据的
复制代码 代码如下:

class ExcelToArrary extends Service{

 public function __construct() {

     /*导入phpExcel核心类    注意 :你的路径跟我不一样就不能直接复制*/
     include_once('./Excel/PHPExcel.php');
 }

/**

* 读取excel $filename 路径文件名 $encode 返回数据的编码 默认为utf8

*以下基本都不要修改

*/

public function read($filename,$encode='utf-8'){

          $objReader = PHPExcel_IOFactory::createReader('Excel5');

          $objReader->setReadDataOnly(true);

          $objPHPExcel = $objReader->load($filename);

          $objWorksheet = $objPHPExcel->getActiveSheet();

    $highestRow = $objWorksheet->getHighestRow();
    $highestColumn = $objWorksheet->getHighestColumn();
      $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
      $excelData = array();
    for ($row = 1; $row         for ($col = 0; $col                  $excelData[$row][] =(string)$objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
           }
         }
        return $excelData;

    }    

 }


第四,以上就是导入的全部内容,phpExcel包附在最后。

(二)Excel的导出(相对于导入简单多了)

第一,先查出数据库里面要生成Excel的数据,如:

$data= M('User')->findAll();   //查出数据
$name='Excelfile';    //生成的Excel文件文件名
$res=service('ExcelToArrary')->push($data,$name);

第二,ExcelToArrary类,用来引用phpExcel并处理数据的   

复制代码 代码如下:

class ExcelToArrary extends Service{

       public function __construct() {

              /*导入phpExcel核心类    注意 :你的路径跟我不一样就不能直接复制*/
               include_once('./Excel/PHPExcel.php');
       }

     /* 导出excel函数*/
    public function push($data,$name='Excel'){

          error_reporting(E_ALL);
          date_default_timezone_set('Europe/London');
         $objPHPExcel = new PHPExcel();

        /*以下是一些设置 ,什么作者  标题啊之类的*/
         $objPHPExcel->getProperties()->setCreator("转弯的阳光")
                               ->setLastModifiedBy("转弯的阳光")
                               ->setTitle("数据EXCEL导出")
                               ->setSubject("数据EXCEL导出")
                               ->setDescription("备份数据")
                               ->setKeywords("excel")
                              ->setCategory("result file");
         /*以下就是对处理Excel里的数据, 横着取数据,主要是这一步,其他基本都不要改*/
        foreach($data as $k => $v){

             $num=$k+1;
             $objPHPExcel->setActiveSheetIndex(0)

                         //Excel的第A列,uid是你查出数组的键值,下面以此类推
                          ->setCellValue('A'.$num, $v['uid'])   
                          ->setCellValue('B'.$num, $v['email'])
                          ->setCellValue('C'.$num, $v['password'])
            }

            $objPHPExcel->getActiveSheet()->setTitle('User');
            $objPHPExcel->setActiveSheetIndex(0);
             header('Content-Type: application/vnd.ms-excel');
             header('Content-Disposition: attachment;filename="'.$name.'.xls"');
             header('Cache-Control: max-age=0');
             $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
             $objWriter->save('php://output');
             exit;
      }


第三,以上就是导出的全部内容,phpExcel包附在最后。
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

Video Face Swap

Video Face Swap

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

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)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

Framework Security Features: Protecting against vulnerabilities. Framework Security Features: Protecting against vulnerabilities. Mar 28, 2025 pm 05:11 PM

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

What are Enumerations (Enums) in PHP 8.1? What are Enumerations (Enums) in PHP 8.1? Apr 03, 2025 am 12:05 AM

The enumeration function in PHP8.1 enhances the clarity and type safety of the code by defining named constants. 1) Enumerations can be integers, strings or objects, improving code readability and type safety. 2) Enumeration is based on class and supports object-oriented features such as traversal and reflection. 3) Enumeration can be used for comparison and assignment to ensure type safety. 4) Enumeration supports adding methods to implement complex logic. 5) Strict type checking and error handling can avoid common errors. 6) Enumeration reduces magic value and improves maintainability, but pay attention to performance optimization.

See all articles