简单有效的php生成excel文件源码

PHP 1642 0 2013-07-25

简单有效的php生成excel文件源码

一种最好用的php生成excel的代码 适用于windows和linux

<?php

function xlsBOF() {
 echo pack("ssssss", 0x809, 0x8, 0x0, 0x10, 0x0, 0x0);
 return;
}
function xlsEOF() {
 echo pack("ss", 0x0A, 0x00);
 return;
}
function format( $STR ){
 $STR = str_replace( "\"", "", $STR );
 if ( strpos( $STR, "," ) ){
  $STR = "\"".$STR."\"";
 }
 $STR = iconv( "utf-8", "gb2312", $STR );
 return $STR;
}
function xlsWriteNumber($Row, $Col, $Value) {
 echo pack("sssss", 0x203, 14, $Row, $Col, 0x0);
 echo pack("d", $Value);
 return;
}
function xlsWriteLabel($Row, $Col, $Value ) {
 $L = strlen($Value);
 echo pack("ssssss", 0x204, 8 + $L, $Row, $Col, 0x0, $L);
 echo $Value;
 return;
}
function write_excel_line($hang,$lie,$val){
 if(is_numeric($val)){
  xlsWriteNumber($hang,$lie,$val);
 }else{
  xlsWriteLabel($hang,$lie,$val);
 }
}
$mktime = mktime();
header('Content-Type: text/html; charset=utf-8');
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Disposition: attachment;filename=$mktime.xls ");
header("Content-Transfer-Encoding: binary ");
// XLS Data Cell
xlsBOF();
xlsWriteLabel(0, 0, format('单元格A1'));
xlsWriteLabel(0, 1, format('单元格B1'));
xlsWriteLabel(0, 2, format('单元格C1'));
write_excel_line(1, 0, 'A2');
write_excel_line(1, 1, 'B2');
write_excel_line(1, 2, 'C2');
write_excel_line(2, 0, 'A3');
write_excel_line(2, 1, 'B3');
write_excel_line(2, 2, 'C3');
write_excel_line(3 , 0, '40');
write_excel_line(3 , 1, '41');
write_excel_line(3 , 2, '42');
xlsEOF();
exit();
?>

我加入了编码转换,解决了中文乱码问题,和写入时的判断。(代码文件存为utf-8)

这种不用借助类库,是一种非常轻巧的实现办法。。

上一篇:PHP编码转换: UTF-8 =&gt; gb2312

下一篇:php二维码接口生成,谷歌(google)API范例

讨论数量:0

请先登录再发表讨论。 2024-04-30

天涯网魂
3 杠 5 星
TA 的文章
TA 的随言
TA 的资源链