萬盛學電腦網

 萬盛學電腦網 >> 網絡編程 >> php編程 >> php中使用PHPExcel操作excel(xls)文件

php中使用PHPExcel操作excel(xls)文件

   PHPExcel是php的一個插件,它可以實現讀取excel文件也就是xls文件了,下面我們就來看一個PHPExcel操作excel(xls)文件例子,希望能幫助到各位。

  讀取中文的xls、csv文件會有問題,網上找了下資料,發現PHPExcel類庫好用  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();
        //設置文檔屬性,設置中文會產生亂碼,待完善...
        // $objPHPExcel->getProperties()->setCreator("雲舒")
                             // ->setLastModifiedBy("雲舒")
                             // ->setTitle("產品URL導出")
                             // ->setSubject("產品URL導出")
                             // ->setDescription("產品URL導出")
                             // ->setKeywords("產品URL導出");
        $objPHPExcel->setActiveSheetIndex(0);
        
        $cols = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        //設置www.111cn.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,支持關聯數組和數字索引數組
     

copyright © 萬盛學電腦網 all rights reserved