Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/database/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用php将sql postgres查询导出到excel_Php_Sql_Postgresql - Fatal编程技术网

使用php将sql postgres查询导出到excel

使用php将sql postgres查询导出到excel,php,sql,postgresql,Php,Sql,Postgresql,嘿,伙计们,我开发了这个php应用程序,我希望它能够将数据正确地导出到excel文档中,这样每个列标题都会与该列中的所有数据一起导出。这是我到目前为止所做的,但它不能正常工作,因为所有列都显示在一行中。我怎样才能实现我想要的?有人请帮助我。这是当前的实施方式: <?php require_once('connections/pgconn.php'); function cleanData(&$str) { $str = preg_replace("/\t/", "\\t", $

嘿,伙计们,我开发了这个php应用程序,我希望它能够将数据正确地导出到excel文档中,这样每个列标题都会与该列中的所有数据一起导出。这是我到目前为止所做的,但它不能正常工作,因为所有列都显示在一行中。我怎样才能实现我想要的?有人请帮助我。这是当前的实施方式:

<?php require_once('connections/pgconn.php');


function cleanData(&$str)
{
$str = preg_replace("/\t/", "\\t", $str);
$str = preg_replace("/\r?\n/", "\\n", $str);
if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
}

// filename for download
$filename = "website_data_" . date('Ymd') . ".xls";

header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: application/vnd.ms-excel");

$flag = false;
$result = pg_query("SELECT to_char (a.CALLDATE,'yyyymm') as month,min(a.calldate) as      start_time,max(a.calldate) as end_time,
     ceil(SUM (a.CALLDURATION::integer) / 60) AS minutes,
     COUNT (DISTINCT a.IDENTIFIANT) AS distinct_callers,
a.zoneiddest as country_code,b.country
FROM cdr_data a,COUNTRY_CODES b
WHERE  a.CALLSUBCLASS = '002'
     AND  a.CALLCLASS = '008'
and a.zoneiddest::integer > 0
AND SUBSTR (a.CALLEDNUMBER, 1, 2) NOT IN
('77', '78', '75', '70', '71', '41', '31', '39', '76','79')

and not substr(a.zoneiddest , 1 ,3) in ('254','255','256','211','257','250','256')
and trim(a.zoneiddest)  = trim(b.country_code)
GROUP BY to_char (a.CALLDATE,'yyyymm') ,a.zoneiddest,b.country
ORDER BY 1") or die('Query failed!');

while(false !== ($row = pg_fetch_assoc($result))) {
if(!$flag) {
  // display field/column names as first row
  echo implode("\t", array_keys($row)) . "\r\n";
  $flag = true;
}
array_walk($row, 'cleanData');
echo implode("\t", array_values($row)) . "\r\n";
}
exit;
?>

我建议将您的查询导出为CSV,告诉PHP将HTTP响应创建为“应用程序/ms excel”内容类型,以便IE将自动启动excel,在具有列名的列中导入CSV:

$query = "COPY (SELECT .... ) TO '/path/reachable/with/php/file.csv' CSV;"
通过这种方式,您可以将CSV保存为服务器上的文件,并在PHP中随时检索它

$file = file_get_contents('/path/reachable/with/php/file.csv');
header('Content-Type: application/ms-excel');
echo $file;

你真的想要一个Excel文件,还是一个简单的CSV文件?我想要一个Excel文件严格地看一下一些用于编写Excel文件的库,例如PHPExcel()或中列出的那些,看看它们能做些什么让我检查它们。不过,我不想从上面的代码中走得太远。您现有的代码在很大程度上保持不变,但是您没有响应内爆,而是设置了单元格值