1

我正在尝试开发一种功能,用于将报告内容导出到 xls 文件,并为用户提供下载 xls 文件以获取他们在网页上看到的结果的选项。以下是我尝试过的代码:

<?php
class export
{
 public function exportxls($cols,$values)
{
function xlsBOF() {
    echo pack("ssssss", 0x809, 0x8, 0x0, 0x10, 0x0, 0x0);
}
function xlsEOF() {
    echo pack("ss", 0x0A, 0x00);
}
function xlsWriteNumber($Row, $Col, $Value) {
    echo pack("sssss", 0x203, 14, $Row, $Col, 0x0);
    echo pack("d", $Value);
}
function xlsWriteLabel($Row, $Col, $Value) {
    $L = strlen($Value);
    echo pack("ssssss", 0x204, 8 + $L, $Row, $Col, 0x0, $L);
    echo $Value;
} 
// prepare headers information
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Disposition: attachment; filename=\"export_".date("Y-m-d").".xls\"");
header("Content-Transfer-Encoding: binary");
header("Pragma: no-cache");
header("Expires: 0");
// start exporting
xlsBOF();

$j=1;
$ret = array_map (
  function ($_) {return explode (',', $_);},
  explode (';', $values)
);




$colarray=explode(',',$cols);



$number=count($colarray);



for($i=0;$i<$number;$i++)
{
   xlsWriteLabel(0,$i,$colarray[$i]); 
}
foreach($ret as $key->$value)
{ 

xlsWriteLabel($j,$key,$value[$key]);
$j=$j+1;
}

xlsEOF();
}
}
?>

这是调用函数的索引文件:

<?php
include 'newxls.php';
$obj=new export();
$obj->exportxls("id,name,class","1,var,btech;2,man,mtech");
?>

请帮帮我;我没有在 excel 文件中获得所需的输出。提前致谢

4

2 回答 2

1

您的代码看起来不错,除了需要进行少量更改

更改此代码

foreach($ret as $key->$value)
{ 

 xlsWriteLabel($j,$key,$value[$key]);
 $j=$j+1;
}

换成这个

foreach ($ret as $key => $value) {
    foreach($value as $k=>$v){
        xlsWriteLabel($j, $k, $v);                
    }            
     $j = $j + 1;
}

所有剩余的代码看起来都很好。

于 2013-08-12T06:23:22.130 回答
0

尝试这个,

$filename ="excelreport";
function exportexcel($fields = array(), $values = array()){

  foreach($fields as $field){
    $contents .= $field." \t";
  }

  $contents. = " \n";

  foreach($values as $value){
     $contents.= $value[0]. " \t";
     $contents.= $value[1]. " \t";                             
     $contents.= $value[2]. " \n";                             
  }
  return $contents;
}

header('Content-type: application/ms-excel');
header("Content-Disposition: attachment; filename=". $filename . date("Y-m-d-H-i") .".xls");
header("Cache-Control: no-cache, must-revalidate");
$contents = exportexcel(array("id,name,class"),array(array('1','test','btech'),array('2','man','mtech')));
echo $contents;
于 2013-08-12T06:01:38.507 回答