当前位置: 移动技术网 > IT编程>开发语言>PHP > php中使用PHPExcel读写excel(xls)文件的方法

php中使用PHPExcel读写excel(xls)文件的方法

2018年07月15日  | 移动技术网IT编程  | 我要评论

本文实例讲述了php中使用phpexcel读写excel(xls)文件的方法,非常实用。分享给大家供大家参考之用。具体方法如下:

很多php类库在读取中文的xls、csv文件时会有问题,网上找了下资料,发现phpexcel类库好用,官网地址为:http://phpexcel.codeplex.com/。现将phpexcel读写excel的方法分别叙述如下:

1、读取xls文件内容

<?php
  //向xls文件写入内容
  error_reporting(e_all);
  ini_set('display_errors', true);  
  include 'classes/phpexcel.php';      
  include 'classes/phpexcel/iofactory.php'; 
  //$data:xls文件内容正文
  //$title:xls文件内容标题
  //$filename:导出的文件名
  //$data和$title必须为utf-8码,否则会写入false值
  function write_xls($data=array(), $title=array(), $filename='report'){
    $objphpexcel = new phpexcel();
    //设置文档属性,设置中文会产生乱码,需要转换成utf-8格式!!
    // $objphpexcel->getproperties()->setcreator("云舒")
               // ->setlastmodifiedby("云舒")
               // ->settitle("产品url导出")
               // ->setsubject("产品url导出")
               // ->setdescription("产品url导出")
               // ->setkeywords("产品url导出");
    $objphpexcel->setactivesheetindex(0);
    
    $cols = 'abcdefghijklmnopqrstuvwxyz';
    //设置www.jb51.net标题
    for($i=0,$length=count($title); $i<$length; $i++) {
      //echo $cols{$i}.'1';
      $objphpexcel->getactivesheet()->setcellvalue($cols{$i}.'1', $title[$i]);
    }
    //设置标题样式
    $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_alignment::horizontal_right,
        ),
        'borders' => array(
          'top'   => array(
            'style' => phpexcel_style_border::border_thin
          )
        ),
        'fill' => array(
          'type'    => phpexcel_style_fill::fill_gradient_linear,
          'rotation'  => 90,
          'startcolor' => array(
            'argb' => 'ffa0a0a0'
          ),
          'endcolor'  => array(
            'argb' => 'ffffffff'
          )
        )
      )
    );
    
    $i = 0;
    foreach($data as $d) { //这里用foreach,支持关联数组和数字索引数组
      $j = 0;
      foreach($d as $v) {  //这里用foreach,支持关联数组和数字索引数组
        $objphpexcel->getactivesheet()->setcellvalue($cols{$j}.($i+2), $v);
        $j++;
      }
       $i++;
    }
    // 生成2003excel格式的xls文件
    header('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(
    array(1111,'名称','品牌','商品名','//www.jb51.net'),
    array(1111,'名称','品牌','商品名','//www.jb51.net'),
    array(1111,'名称','品牌','商品名','//www.jb51.net'),
    array(1111,'名称','品牌','商品名','//www.jb51.net'),
    array(1111,'名称','品牌','商品名','//www.jb51.net'),
  );
  write_xls($array,array('商品id','供应商名称','品牌','商品名','url'),'report');
  
?>

2、向xls文件写内容

<?php
  //获取数据库数据(mysqli预处理学习)
  $config = array(
    'db_type'=>'mysql',
    'db_host'=>'localhost',
    'db_name'=>'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()) {  //兼容 < php5.2.9 oo way:$mysqli->connect_error
      die("连接失败,错误码:".mysqli_connect_errno()."错误信息:".mysqli_connect_error());
    }
    //设置连接数据库的编码,不要忘了设置
    $mysqli->set_charset("gbk");
    //中文字符的编码要与数据库一致,若没设置,结果为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;  //得到的是gbk码(同数据库编码)
  }  
  $id = getproductidbyname('%伊奈卫浴伊奈分体座便器%');
  var_dump($id);
?>

希望本文所述对大家的php程序设计有所帮助

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网