search
HomeBackend DevelopmentPHP TutorialThinkPHP framework implements the method of exporting excel data (based on PHPExcel)

This article mainly introduces the method of exporting excel data in the ThinkPHP framework, and analyzes the related implementation techniques of thinkPHP adding org extension to export Excel data based on PHPExcel in the form of examples. Friends in need can refer to the following

The example in this article describes how the ThinkPHP framework implements exporting excel data. Share it with everyone for your reference, the details are as follows:

In the ThinkPHP framework, an example of how to export excel data:

Before operation, the ORG library should be added to the extension directory of the system framework. That is to include the ThinkPHP\Extend\Library\ORG\Util\PHPExcel.class.php file and its related supporting files.

<?php
header("Content-type: text/html; charset=utf-8");
class MesTestAction extends Action {
  //测试导出excel数据
  public function tpGetExcel() {
    //创建对象
    import("ORG.Util.PHPExcel"); //从PHPExcel目录导PHPExcel.php类文件
    $excel = new PHPExcel();
    $data = M()->query(&#39;SELECT userid,username,stepgoal FROM tp_data_user LIMIT 2775&#39;);
    //Excel表格式,这里简略写了3列
    $letter = array(&#39;A&#39;,&#39;B&#39;,&#39;C&#39;);
    //表头数组
    $tableheader = array(&#39;userid&#39;,&#39;用户名&#39;,&#39;目标步数&#39;);
    $count= count($data);//总的数据行数
    $listNum = 500;//每个sheet页最大数据行数
    $num = ceil($count/$listNum);//sheet页个数
    $MuitData = array_chunk($data,$listNum,false);//分割总的数据,每页最多$listNum行有效数据
  //var_dump($MuitData);//die(&#39;as&#39;);
  //缺省情况下,PHPExcel会自动创建第一个SHEET,其索引SheetIndex=0
  //设置 当前处于活动状态的SHEET 为PHPExcel自动创建的第一个SHEET
  $excel->setActiveSheetIndex(0); //objPHPExcel
  //设置sheet的title
  $excel->getActiveSheet()->setTitle(&#39;考核得分第&#39;.&#39;1&#39;.&#39;页&#39;);
  //设置sheet的列名称
    for($k = 0; $k < count($tableheader); ++$k) {
      $excel->getActiveSheet()->setCellValue("$letter[$k]".&#39;1&#39;,"$tableheader[$k]");//第一行数据
    }
  //填充表格信息 处理第1块数据
  $crrntSheetLineNo = count($MuitData[0]) + 1;
  for ( $j = 2; $j <= $crrntSheetLineNo; ++$j) { //遍历每一行
    $k = 0;
    foreach ( $MuitData[0][$j - 2] as $key => $value ) {//遍历具体行的某一列
      $excel->getActiveSheet()->setCellValue("$letter[$k]".$j,"$value");//第$k列 第$j行
      $k++;
    }
  }
  //后续的sheet页及数据块
    for ( $i = 1; $i <$num; ++$i) {
      //创建第$i个sheet
      $msgWorkSheet = new PHPExcel_Worksheet($excel, &#39;考核得分第&#39;.($i + 1).&#39;页&#39;); //创建一个工作表
      $excel->addSheet($msgWorkSheet); //插入工作表
      $excel->setActiveSheetIndex($i); //切换到新创建的工作表
      //设置sheet的列名称
      for($k = 0; $k < count($tableheader); ++$k) {
        $excel->getActiveSheet()->setCellValue("$letter[$k]1","$tableheader[$k]");//第一行数据
      }
      //填充表格信息 处理第$i块数据
    $crrntSheetLineNo = count($MuitData[$i]) + 1; //var_dump($crrntSheetLineNo);var_dump($MuitData[$i-1]);die(&#39;as&#39;);
      for ( $j = 2; $j <= $crrntSheetLineNo; ++$j) { //遍历每一行
        $k = 0;
        foreach ( $MuitData[$i-1][$j - 2] as $key => $value ) {//遍历具体行的某一列
          $excel->getActiveSheet()->setCellValue("$letter[$k]$j","$value");//第$k列 第$j行
          ++$k;
        }
      }
      usleep(100);
    }
    //创建Excel输出对象
    $filename = "大奖赛培训考核得分.xls";
    $write = new PHPExcel_Writer_Excel5($excel);
    ob_end_clean();//清除缓冲区,避免乱码
  /*
  //输出到本地
    $write->save( iconv(&#39;utf-8&#39;, &#39;gbk&#39;, $filename) );
  */
    //输出到浏览器
    header("Pragma: public");
    header("Expires: 0");
    header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
    header("Content-Type:application/force-download");
    header("Content-Type:application/vnd.ms-execl");
    header("Content-Type:application/download");
    header(&#39;Content-Type:application/octet-stream&#39;);
    $encoded_filename = urlencode($filename);
    $encoded_filename = str_replace("+", "%20", $encoded_filename);
    $ua = $_SERVER["HTTP_USER_AGENT"];
    if (preg_match("/MSIE/", $ua)) {
      header(&#39;Content-Disposition: attachment; filename="&#39; . $encoded_filename . &#39;"&#39;);
    } else if (preg_match("/Firefox/", $ua)) {
      header(&#39;Content-Disposition: attachment; filename*="utf8\&#39;\&#39;&#39; . $filename . &#39;"&#39;);
    } else {
      header(&#39;Content-Disposition: attachment; filename="&#39; . $filename . &#39;"&#39;);
    }
    header("Content-Transfer-Encoding:binary");
    $write->save(&#39;php://output&#39;);
  }
}
?>

The above is the entire content of this article, thank you for reading. Please pay attention to the PHP Chinese website for more information!

Related recommendations:

ThinkPHP framework implements data addition, deletion and modification methods

thinkPHP framework implements user remote login reminder

The above is the detailed content of ThinkPHP framework implements the method of exporting excel data (based on PHPExcel). For more information, please follow other related articles on the PHP Chinese website!

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
How does PHP identify a user's session?How does PHP identify a user's session?May 01, 2025 am 12:23 AM

PHPidentifiesauser'ssessionusingsessioncookiesandsessionIDs.1)Whensession_start()iscalled,PHPgeneratesauniquesessionIDstoredinacookienamedPHPSESSIDontheuser'sbrowser.2)ThisIDallowsPHPtoretrievesessiondatafromtheserver.

What are some best practices for securing PHP sessions?What are some best practices for securing PHP sessions?May 01, 2025 am 12:22 AM

The security of PHP sessions can be achieved through the following measures: 1. Use session_regenerate_id() to regenerate the session ID when the user logs in or is an important operation. 2. Encrypt the transmission session ID through the HTTPS protocol. 3. Use session_save_path() to specify the secure directory to store session data and set permissions correctly.

Where are PHP session files stored by default?Where are PHP session files stored by default?May 01, 2025 am 12:15 AM

PHPsessionfilesarestoredinthedirectoryspecifiedbysession.save_path,typically/tmponUnix-likesystemsorC:\Windows\TemponWindows.Tocustomizethis:1)Usesession_save_path()tosetacustomdirectory,ensuringit'swritable;2)Verifythecustomdirectoryexistsandiswrita

How do you retrieve data from a PHP session?How do you retrieve data from a PHP session?May 01, 2025 am 12:11 AM

ToretrievedatafromaPHPsession,startthesessionwithsession_start()andaccessvariablesinthe$_SESSIONarray.Forexample:1)Startthesession:session_start().2)Retrievedata:$username=$_SESSION['username'];echo"Welcome,".$username;.Sessionsareserver-si

How can you use sessions to implement a shopping cart?How can you use sessions to implement a shopping cart?May 01, 2025 am 12:10 AM

The steps to build an efficient shopping cart system using sessions include: 1) Understand the definition and function of the session. The session is a server-side storage mechanism used to maintain user status across requests; 2) Implement basic session management, such as adding products to the shopping cart; 3) Expand to advanced usage, supporting product quantity management and deletion; 4) Optimize performance and security, by persisting session data and using secure session identifiers.

How do you create and use an interface in PHP?How do you create and use an interface in PHP?Apr 30, 2025 pm 03:40 PM

The article explains how to create, implement, and use interfaces in PHP, focusing on their benefits for code organization and maintainability.

What is the difference between crypt() and password_hash()?What is the difference between crypt() and password_hash()?Apr 30, 2025 pm 03:39 PM

The article discusses the differences between crypt() and password_hash() in PHP for password hashing, focusing on their implementation, security, and suitability for modern web applications.

How can you prevent Cross-Site Scripting (XSS) in PHP?How can you prevent Cross-Site Scripting (XSS) in PHP?Apr 30, 2025 pm 03:38 PM

Article discusses preventing Cross-Site Scripting (XSS) in PHP through input validation, output encoding, and using tools like OWASP ESAPI and HTML Purifier.

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 Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

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.