将数组导出到Excel

我试图导出一个数组的数组,以Excel。 我把它设置为一个头variables,和一个数据variables,基本上build立一个巨大的string,在出口执行。 但是,只有头部variables正在经历。 让我显示一些代码:

这是设置参数:

str_replace(" ", "_", $getData['name']); $filename = $getData['name']."_summary.xls"; header("Content-Type: application/x-msdownload"); header("Content-Disposition: attachment; filename=\"$filename\""); header("Pragma: no-cache"); header("Expires: 0"); 

哪一个去函数来获取信息:

 foreach($tempRS as $key=>$value) { foreach($value as $iKey=>$iValue) { if($count == 6) { $iValue = str_replace('"', '""', $iValue); $iValue = '"'.$iValue.'"'."\n"; $data .= trim($iValue); $count = 0; } else { $iValue = str_replace('"', '""', $iValue); $iValue = '"'.$iValue.'"'."\t"; $data .= trim($iValue); $count++; } } } $header = "ROW HEADER 1\tROW HEADER 2\tROW HEADER 3\tROW HEADER 4\tROW HEADER 5\tROW HEADER 6\n"; print "$header\n$data"; 

我似乎无法弄清楚为什么我失去了出口的$数据variables。

为什么不只是fputcsv()为你生成CSV数据呢? 或者更好的做法是,不要将.csv伪装成Excel文件,而是使用PHPExcel输出本机.xls / .xlsx,并在生成的电子表格中实际使用格式和公式。

首先,使用回声,而不是打印。 打印导致开销的负载,因为它既返回和回显数据。

其次,不要把variables放在引号内,使用

 echo $header ."\n".$data; 

为了得到你的问题,foreach循环实际上循环? 你有没有检查$数据,如果它包含任何数据?

更好的解决scheme可能是这样的:

 $header = ''; echo $header; foreach() loop here { //echo the data here instead of putting it in a variable } 

或者,也许更好,使用http://nl.php.net/fputcsv

我testing了你的代码,看来你的trim()方法正在修剪你的\n\t

如果你删除它,你的代码应该没问题。

这是我的代码,导出excel中的产品数组。

这个代码只有一个小问题:因为格式问题,Excel不想打开它,但是如果在提示错误消息时单击“是”,那么您将会没事的。

没有问题,但开放的办公室

正在修复…

 $filename = "products_exports " . date("Ymd H_i_s") . ".xls"; /** * Tell the browser to download an excel file. */ header("Content-Type: application/x-msdownload; charset=utf-8"); header("Content-Disposition: attachment; filename=\"$filename\""); header("Pragma: no-cache"); header("Expires: 0"); /** * The header of the table * @var string */ $header = ""; /** * All the data of the table in a formatted string * @var string */ $data = ""; //We fill in the header foreach ($productArray as $i => $product) { $count = 0; foreach ($product as $key => $value) { if($count == count((array)new Product("")) - 1){ $header.= $key; } else{ $header.= $key . "\t"; $count++; } } break; /*One loop is enough to get the header !*/ } //And then the data by the product and all the categories /*Where $productArray = This can be your custom array of object. eg. array[0] = new YouCustomObject(your params...); */ foreach ($productArray as $i => $product) { $count = 0; foreach ($product as $key => $value) { if($count == count((array)new Product("")) - 1){ $value = str_replace('"', '""', $value); $value = '"' . $value . '"' . "\n"; $data .= $value; $count = 0; } else{ $value = str_replace('"', '""', $value); $value = '"' . $value . '"' . "\t"; $data .= $value; $count++; } } } echo $header ."\n". $data;