<script>ec(2);</script>
class Excel{
var $header = "
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 = "";
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 .= "
" . $v . " | ";
} else {
$cells .= "
" . $v . " | ";
}
} else {
$cells .= "
" . $v . " | ";
}
endforeach;
// transform $cells content into one row
$this->lines[] = "
" . $cells . "
";
}
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_title . ""> ";
echo " ";
echo implode (" ", $this->lines);
echo "
";
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");
*/
?>