search
HomeBackend DevelopmentPHP Tutorial利用phpExcel实现Excel数据的导入导出(全步骤详细解析)_PHP

很多文章都有提到关于使用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
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
Working with Flash Session Data in LaravelWorking with Flash Session Data in LaravelMar 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, ReactBuild a React App With a Laravel Back End: Part 2, ReactMar 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

cURL in PHP: How to Use the PHP cURL Extension in REST APIscURL in PHP: How to Use the PHP cURL Extension in REST APIsMar 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.

Simplified HTTP Response Mocking in Laravel TestsSimplified HTTP Response Mocking in Laravel TestsMar 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' =>

12 Best PHP Chat Scripts on CodeCanyon12 Best PHP Chat Scripts on CodeCanyonMar 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

Notifications in LaravelNotifications in LaravelMar 04, 2025 am 09:22 AM

In this article, we're going to explore the notification system in the Laravel web framework. The notification system in Laravel allows you to send notifications to users over different channels. Today, we'll discuss how you can send notifications ov

Explain the concept of late static binding in PHP.Explain the concept of late static binding in PHP.Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

PHP Logging: Best Practices for PHP Log AnalysisPHP Logging: Best Practices for PHP Log AnalysisMar 10, 2025 pm 02:32 PM

PHP logging is essential for monitoring and debugging web applications, as well as capturing critical events, errors, and runtime behavior. It provides valuable insights into system performance, helps identify issues, and supports faster troubleshoot

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

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

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor