天天看點

php xls導出檔案到本地_php如何導出excel檔案

* Simple excel generating from PHP5

*

* @package Utilities

* @license http://www.opensource.org/licenses/mit-license.php

* @author Oliver Schwarz

* @version 1.0*/

classExcel_XML

{

private $header = "<?xml version=\"1.0\" encoding=\"%s\"?\>\n";

private $footer = "";

private $lines = array();

private $sEncoding;

private $bConvertTypes;

private $sWorksheetTitle;

public function __construct($sEncoding = 'UTF-8', $bConvertTypes = false, $sWorksheetTitle = 'Table1')

{$this->bConvertTypes = $bConvertTypes;$this->setEncoding($sEncoding);$this->setWorksheetTitle($sWorksheetTitle);

}

public function setEncoding($sEncoding)

{$this->sEncoding = $sEncoding;

}

public function setWorksheetTitle ($title)

{$title = preg_replace ("/[\\\|:|\/|\?|\*|\[|\]]/", "", $title);$title = substr ($title, 0, 31);$this->sWorksheetTitle = $title;

}

private function addRow ($array)

{$cells = "";foreach ($array as $k => $v):

$type = 'String';if ($this->bConvertTypes === true && is_numeric($v)):

$type = 'Number';endif;$v = htmlentities($v, ENT_COMPAT, $this->sEncoding);$cells .= "" . $v . "\n";endforeach;$this->lines[] = "\n" . $cells . "\n";

}

public function addArray ($array)

{foreach ($array as $k => $v)$this->addRow ($v);

}

public function generateXML ($filename = 'excel-export')

{//correct/validate filename

$filename = preg_replace('/[^aA-zZ0-9\_\-]/', '', $filename);//deliver header (as recommended in php manual)

header("Content-Type: application/vnd.ms-excel; charset=" . $this->sEncoding);header("Content-Disposition: inline; filename=\"" . $filename . ".xls\"");//print out document to the browser

// need to use stripslashes for the damn ">"

echo stripslashes (sprintf($this->header, $this->sEncoding));echo "\nsWorksheetTitle . "\">\n

\n\n";echo $this->footer;

}

}?>