Thinkphp5.0 How to import and export

Source: Internet
Author: User
Thinkphp is a free, open-source, fast, simple object-oriented, lightweight PHP development framework that follows the Apache2 Open source protocol and is designed to simplify enterprise application development and Agile Web application development. This article we mainly share with you Thinkphp5.0 how to import and export.

First go to the official website http://phpexcel.codeplex.com/Download the latest Phpexcel

thinkphp extension classes are generally placed under extend

Write Import and export public method, easy to call in the controller

Import an Excel file

/** * Import Excel File * @param  string $file Excel file path * @return        array of contents of Excel file */function Import_excel ($file) {    / /Determine what format the file is    $type = PathInfo ($file);    $type = Strtolower ($type ["extension"]);    $type = $type = = = ' csv '? $type: ' Excel5 ';    Ini_set (' max_execution_time ', ' 0 ');    Loader::import (' Phpexcel.phpexcel ');     Determine which format to use    $objReader = Phpexcel_iofactory::createreader ($type);    $objPHPExcel = $objReader->load ($file);    $sheet = $objPHPExcel->getsheet (0);    Total number of rows obtained    $highestRow = $sheet->gethighestrow ();    Total number of columns obtained    $highestColumn = $sheet->gethighestcolumn ();     Iterate through the Excel file, read a line, insert a    $data =array ();    Reads data from the first line for    ($j =1; $j <= $highestRow; $j + +) {        //reads data from column A for        ($k = ' a '; $k <= $highestColumn; $k + +) {            //Read cell            $data [$j][]= $objPHPExcel->getactivesheet ()->getcell ("$k $j")->getvalue ();}    }    return $data;}


Array to XLS format Excel file

/** * Array to XLS format for Excel file * @param array $data need to generate arrays of Excel files * @param string $filename generated Excel file name * Sample data: $data = Array (NULL, all, (), Array (' Q1 ', ","), Array (' Q 2 ', ",", ","), Array (' Q3 ', ","), Array (' Q4 ', 30, 32, 0),);    */function Create_xls ($data, $filename = ' Simple.xls ') {ini_set (' max_execution_time ', ' 0 ');    Loader::import (' Phpexcel.phpexcel '); $filename =str_replace ('. xls ', ', $filename).    XLS ';    $phpexcel = new Phpexcel ();         $phpexcel->getproperties ()->setcreator ("Maarten Balliauw")->setlastmodifiedby ("Maarten Balliauw") ->settitle ("Office" xlsx Test Document ")->setsubject (" Office "xlsx Test Document")-&        Gt;setdescription ("Test document for Office" XLSX, generated using PHP classes. ") ->setkeywords ("Office openxml PHP")->setcategory ("Test ResUlt file ");    $phpexcel->getactivesheet ()->fromarray ($data);    $phpexcel->getactivesheet ()->settitle (' Sheet1 ');    $phpexcel->setactivesheetindex (0);    Header (' Content-type:application/vnd.ms-excel ');    Header ("Content-disposition:attachment;filename= $filename");    Header (' cache-control:max-age=0 ');    Header (' cache-control:max-age=1 '); Header (' Expires:mon, Jul 1997 05:00:00 GMT '); Date in the past header (' last-modified: '. Gmdate (' d, D M Y h:i:s '). ' GMT '); Always modified header (' Cache-control:cache, Must-revalidate '); http/1.1 header (' pragma:public ');    http/1.0 $objwriter = Phpexcel_iofactory::createwriter ($phpexcel, ' Excel5 ');    $objwriter->save (' php://output '); Exit;} Data to CSV format excle/** * data to CSV format of excle * @param array $data need to go to arrays * @param string $header The Excel header to be generated * @param stri ng $filename generated Excel file name * Example array: $data = Array (' 1,2,3,4,5 ', ' 6,7,8,9,0 ', ' 1,  3,5,6,7 '          ); $header = ' username, password, avatar, gender, mobile number ';        */function create_csv ($data, $header =null, $filename = ' simple.csv ') {//If the header is set manually, place the first row if (!is_null ($header)) {    Array_unshift ($data, $header); }//prevents the file suffix from being added $filename =str_replace ('. csv ', ' ', $filename).    CSV ';    Ob_clean ();    Header ("Content-type:application/octet-stream");    Header ("Accept-ranges:bytes");  Header ("content-disposition:attachment;    Filename= ". $filename);        foreach ($data as $k = + $v) {//If it is a two-dimensional array, turn into one-dimensional if (Is_array ($v)) {$v =implode (', ', $v);        }//Replace swap line $v =preg_replace ('/\s*/', ' ', $v);        Resolving the exported numbers will show the question of scientific notation $v =str_replace (', ', ' \ T, ', $v); Turn into GBK to be compatible with Office garbled questions Echo iconv (' UTF-8 ', ' GBK ', $v). "    \t\r\n "; }}

Examples of Use:

Import principle:

The file to be imported is first uploaded to the server via the Thinkphp method, then the public import method is invoked according to the uploaded path, and the file path of Excel to be imported is as follows

Public Function Importuser () {        $data =import_excel ('./a.xls ');        Print_r ($data);        Exit;    }

The above content is Thinkphp5.0 import and export detailed, hope can help everyone.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.