How to use Phpexcel to read and write Excel (xls) files in PHP _php tips

Source: Internet
Author: User

This example describes the use of Phpexcel read-write Excel (xls) files in PHP, very practical. Share for everyone to use for reference. The specific methods are as follows:

Many PHP class libraries in the reading of Chinese XLS, CSV file will have problems, the Internet to find the next data, found Phpexcel class library easy to use, the official website address: http://phpexcel.codeplex.com/. Phpexcel Read and write Excel are described separately as follows:

1. read xls file contents

<?php//To XLS file writing content error_reporting (E_all);  
  Ini_set (' display_errors ', TRUE);      
  Include ' classes/phpexcel.php '; 
  Include ' classes/phpexcel/iofactory.php '; $data: XLS file content body//$title: XLS file content title//$filename: The exported filename//$data and $title must be utf-8 code, otherwise the false value function Write_xls is written ($da
    Ta=array (), $title =array (), $filename = ' the ') {$objPHPExcel = new phpexcel ();
    Set the document properties, set the Chinese will produce garbled, need to convert to UTF-8 format!! $objPHPExcel->getproperties ()->setcreator ("Yun Shu")//->setlastmodifiedby ("Yun Shu")/
               ->settitle ("Product URL Export")//->setsubject ("Product URL Export")//->setdescription ("Product URL export")
    ->setkeywords ("Product URL export");
    
    $objPHPExcel->setactivesheetindex (0);
    $cols = ' abcdefghijklmnopqrstuvwxyz '; Set www.jb51.net title for ($i =0, $length =count ($title); $i < $length; $i + +) {//echo $cols {$i}. '
      1 '; $objPHPExcel->getactivesheet ()->setcellvalue ($cols {$i}. '
  1 ', $title [$i]);  //Set heading style $titleCount = count ($title); $r = $cols {0}. '
    1 '; $c = $cols {$titleCount}. '
    1 ';
          $objPHPExcel->getactivesheet ()->getstyle ("$r: $c")->applyfromarray (Array (' Font ' => array ( ' Bold ' => true), ' alignment ' => array (' Horizontal ' => phpexcel_style_alignmen T::horizontal_right,), ' Borders ' => array (' Top ' => array (' style ' => PH Pexcel_style_border::border_thin)), ' Fill ' => array (' type ' => phpexcel_sty Le_fill::fill_gradient_linear, ' rotation ' =>, ' StartColor ' => array (' ARGB ' =&gt ;
      ' ffa0a0a0 '), ' EndColor ' => array (' ARGB ' => ' ffffffff '))
    
    )
    );
    $i = 0;
      foreach ($data as $d) {//here with foreach, supports associative arrays and numeric index arrays $j = 0;
       foreach ($d as $v) {//here with foreach, supports associative and numeric indexed arrays $objPHPExcel->getactivesheet ()->setcellvalue ($cols {$j}.
        $i +2), $v);
      $j + +;
    } $i + +;
    ///Generate 2003excel XLS header headers (' Content-type:application/vnd.ms-excel '); Header (' Content-disposition:attachment;filename= '. $filename. ')
    XLS "');

    Header (' cache-control:max-age=0 ');
    $objWriter = Phpexcel_iofactory::createwriter ($objPHPExcel, ' Excel5 ');
  $objWriter->save (' php://output '); $array = Array (1111, ' name ', ' brand ', ' Commodity name ', ' http://www.jb51.net '), Array (1111, ' name ', ' brand ', ' Commodity name ', ' http://www.jb51
    . NET '), array (1111, ' name ', ' brand ', ' Commodity name ', ' http://www.jb51.net '), Array (1111, ' name ', ' brand ', ' Commodity name ', ' http://www.jb51.net '),
  Array (1111, ' name ', ' brand ', ' Commodity name ', ' http://www.jb51.net ');
  
Write_xls ($array, array (' Commodity id ', ' Supplier name ', ' brand ', ' name of commodity ', ' URL '), ' the ' ";
 ?>

2, writing to an XLS file

<?php//Get Database data (mysqli preprocessing learning) $config = Array (' db_type ' => ' mysql ', ' db_host ' => ' localhost ', ' db_na ')
  ME ' => ' test ', ' Db_user ' => ' root ', ' db_pwd ' => ' root ', ' db_port ' => ' 3306 ',);
    function Getproductidbyname ($name) {global $config;
    
    $id = false;
    $mysqli = new Mysqli ($config [' Db_host '], $config [' Db_user '], $config [' db_pwd '], $config [' db_name ']); if (Mysqli_connect_error ()) {//compatible < php5.2.9 OO way: $mysqli->connect_error die ("Connection failed, error code:". Mysqli_connect_err No (). "
    Error message: ". Mysqli_connect_error ());
    //Set the encoding of the connection database, do not forget to set the $mysqli->set_charset ("GBK");
    Chinese character encoding to be consistent with the database, if not set, the result is null $name = Iconv ("Utf-8", "Gbk//ignore", $name); if ($mysqli _stmt = $mysqli->prepare ("SELECT ID from 137_product where name like?")
      {$mysqli _stmt->bind_param ("s", $name);
      $mysqli _stmt->execute ();
      $mysqli _stmt->bind_result ($id);
      $mysqli _stmt->fetch ();
 $mysqli _stmt->close ();   } $mysqli->close ();  return $id;
  Get the GBK code (with database code)} $id = Getproductidbyname ('% Inax sanitary inax split toilet% ');

 Var_dump ($id);?>

Hopefully this article will help you with your PHP program design

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.