PHP - PHPExcel操做xls文件

讀取中文的xls、csv文件會有問題,網上找了下資料,發現PHPExcel類庫好用,官網地址:http://phpexcel.codeplex.com/ php

一、讀取xls文件內容
<?php
    
    //讀取xls
    
    header("Content-Type:text/html;charset=utf-8");
    include 'Classes/PHPExcel.php';            
    include 'Classes/PHPExcel/IOFactory.php';

    function readxls($file, $type) {
        $xlsReader = PHPExcel_IOFactory::createReader($type);  
        $xlsReader->setReadDataOnly(true);
        $xlsReader->setLoadSheetsOnly(true);
        $sheets = $xlsReader->load($file);
        $content = $sheets->getSheet(0)->toArray(); //讀取第一個工做表(注意編號從0開始) 若是讀取多個能夠作一個循環0,1,2,3....
        //獲得二維數組,每一個小數組是excel表格內容的一行 裏面包含此行的每列的數據  
        return $content;
    }
    
    //$type = 'Excel2007'; //設置要解析的Excel類型 Excel5(2003或如下版本)或Excel2007
    $type = 'Excel5';
    $content = readxls('data.xls', $type);
    echo '<pre>';
    var_dump($content);
    echo '</pre>';
    
?>

二、向xls文件寫內容html

 

<?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';
        //設置標題
        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,'名稱','品牌','商品名','http://www.baidu.com'), array(1111,'名稱','品牌','商品名','http://www.baidu.com'), array(1111,'名稱','品牌','商品名','http://www.baidu.com'), array(1111,'名稱','品牌','商品名','http://www.baidu.com'), array(1111,'名稱','品牌','商品名','http://www.baidu.com'), ); write_xls($array,array('商品id','供應商名稱','品牌','商品名','URL'),'report'); ?>

 

三、操做數據庫獲取要寫入的內容
舉個使用mysqli的預處理獲取內容的例子:
<?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 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);
?>

OK...mysql

參考資料:
相關文章
相關標籤/搜索