【问题标题】:Save xls file to directory and download in php将xls文件保存到目录并在php中下载
【发布时间】:2017-05-15 11:56:20
【问题描述】:

我有一个 php 代码,它从 postgres db 中选择一个查询并创建一个 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 文件而不是下载它。

【问题讨论】:

  • 你可以使用output_buffering来做。看看docs
  • 查看answer中的示例。
  • 你的文件名是什么?

标签: php excel postgresql zipfile


【解决方案1】:

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

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

【讨论】:

  • 如果合适的话记得接受答案@Esteann Afonso
【解决方案2】:

您可以使用以下可以正常工作的代码

            $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;
            }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-10
    • 1970-01-01
    • 1970-01-01
    • 2015-08-28
    • 2014-09-01
    • 2012-08-03
    • 1970-01-01
    • 2017-02-13
    相关资源
    最近更新 更多