首页 > php代码 > php生成 execel表格

php生成 execel表格

<?php
class Excel {
    var $header = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
    <Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"
    xmlns:x=\"urn:schemas-microsoft-com:office:excel\"
    xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\"
    xmlns:html=\"http://www.w3.org/TR/REC-html40\">";
    var $footer = "</Workbook>";
    var $lines = array();
    var $worksheet_title = "Table1";
    function addRow($array) {
        // 初始化列
        $cells = "";
        // foreach key -> write value into cells
        foreach ($array as $k => $v)
        {
          // 加个字符串与数字的判断 避免生成的excel出现数字以字符串存储的警告
          if (is_numeric($v)) {
            // 防止首字母为 0 时生成 excel 后 0 丢失
            if (substr($v, 0, 1) == 0) {
              $cells.= "<Cell><Data ss:Type=\"String\">".$v."</Data></Cell>";
            } else {
              $cells.= "<Cell><Data ss:Type=\"Number\">".$v."</Data></Cell>";
              }
            } else {
              $cells.= "<Cell><Data ss:Type=\"String\">".$v."</Data></Cell>";
          }
        }
        // transform $cells content into one row
        $this->lines[] = "<Row> " . $cells . "</Row> ";
    }
    function addArray($array) {
        // 返回数组并保存到单元格中去
        foreach ($array as $k => $v):
            $this->addRow($v);
        endforeach;
    }
    function setWorksheetTitle($title) {
        $title = preg_replace("/[|:|/|?|*|[|]]/", "", $title);
        // 取得标题长度
        $title = substr($title, 0, 31);
        // 赋值
        $this->worksheet_title = $title;
    }
    function generateXML($filename) {
        header("Content-Type: application/vnd.ms-excel; charset=UTF-8");
        header("Content-Disposition: inline; filename=\"" . $filename . ".xls\"");
        echo stripslashes($this->header);
        echo " <Worksheet ss:Name=\"" . $this->worksheet_title . "\"> <Table> ";
        echo "<Column ss:Index=\"1\" ss:AutoFitWidth=\"0\" ss:Width=\"110\"/> ";
        echo implode(" ", $this->lines);
        echo "</Table> </Worksheet> ";
        echo $this->footer;
    }
}
/**
 *  CakePHP中使用方法
 *  注意 ** cakePHP 配置文件 define('DEBUG', 0);
 *
 *  vendor ('Excel');
 *  $doc = array (
 *       0 => array ('中国', '中国人', '中国人民', '123456');
 *  );
 *  $xls = new Excel;
 *  $xls->addArray ( $doc );
 *  $xls->generateXML ("mytest");
 */
/**
 *  非框架使用方法
 *
 *  require_once('excel.php');
 *  $doc = array (
 *       0 => array ('中国', '中国人', '中国人民', '123456');
 *  );
 *  $xls = new Excel;
 *  $xls->addArray ( $doc );
 *  $xls->generateXML ("mytest");
 */


文章地址:http://www.phprm.com/code/2fd1f052c2f90196112dad2623d1f25b.html

转载随意^^请带上本文地址!

标签:none

发表留言