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

inb24sb2  于 2023-04-13  发布在  PHP
关注(0)|答案(3)|浏览(171)

我有一个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文件,而不是下载它。

mefy6pfw

mefy6pfw1#

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

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

o8x7eapl2#

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

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

5m1hhzi43#

使用以下方法下载到excel很容易。有两种方法可以保存输出,使用浏览器下载或下载到特定路径。

$objWriter = PHPExcel_IOFactory::createWriter($PHPExcel, 'Excel2007');
ob_start(); // We'll be outputting an excel file 
header('Content-type: application/vnd.ms-excel'); 
// It will be called file.xlsx 
header('Content-Disposition: attachment; filename="'.$filename.'.xlsx"'); 
----------------
//To download to a specific path
$objWriter->save('path/'.$filename.'.xlsx');
----------------
//Write file to browser
$objWriter->save('php://output');

相关问题