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

原文链接 http://hi.baidu.com/viwovi/blog/item/710e5b370f52d4380b55a9ff.html

<?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导出excel)