将xls文件保存到目录并在php中下载

时间:2017-05-15 11:56:20

标签: php excel postgresql zipfile

我有一个php代码,它从postgres数据库中选择一个查询并创建一个xls文件并下载相同的文件。代码如下:

    <?php

$xls_filename = 'filename.xls'; // Define Excel (.xls) file name

$Connect = pg_connect ("host=xxxx port=5432 dbname=xxxx user=xxx  password=xxx");

$sql = 'SELECT * FROM "tablename"';

$result = pg_query($sql);

header("Content-Type: application/xls");
header("Content-Disposition: attachment; filename=$xls_filename");
header("Pragma: no-cache");
header("Expires: 0");

// Define separator (defines columns in excel &amp; tabs in word)
$sep = "\t"; // tabbed character 

// Start of printing column names as names of fields
for ($i = 0; $i<pg_num_fields($result); $i++) {
    echo pg_field_name($result,$i) . "\t";
}

print("\n");
// End of printing column names

// Start while loop to get data
while($row = pg_fetch_row($result))
{
  $schema_insert = "";
  for($j=0; $j<pg_num_fields($result); $j++)
  {
    if(!isset($row[$j])) {
      $schema_insert .= "".$sep;
   }
    elseif ($row[$j] != "") {
      $schema_insert .= "$row[$j]".$sep;
    }
    else {
      $schema_insert .= "".$sep;
    }
  }
  $schema_insert = str_replace($sep."$", "", $schema_insert);
  $schema_insert = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
  $schema_insert .= "\t";
  print(trim($schema_insert));
  print "\n";
  } 
  }

?>

我想压缩这个创建的xls文件而不是下载它。 如何在目录中创建xls文件而不是下载它。

2 个答案:

答案 0 :(得分:0)

问题是你的变量。当你的文件名有空格时,你必须使用如下所示的引号:

header("Content-Type: application/xls");
header("Content-Disposition: attachment; filename='$xls_filename'");

答案 1 :(得分:0)

您可以使用以下正常运行的代码

            $fileNames = WWW_ROOT . 'uploads' . DS . 'export' . DS . 'DYNAMIC_FILE_NAME_'. $ANY_DYNAMIC_PART.'.xls';//Dynamic Path of the directory
            if (file_exists($fileNames)) {
                $file = $fileNames;
                header("Content-Type: application/force-download");
                header("Content-Type: application/octet-stream");
                header("Content-Type: application/download");
                header("Content-Disposition: attachment; filename=\"NEWFILENAME.xls\"");
                header("Content-Transfer-Encoding: binary");
                header("Pragma: no-cache");
                header("Expires: 0");
                readfile($fileNames);exit;
            }