【问题标题】:PHPExcel: Automatically download and open an Excel filePHPExcel:自动下载并打开 Excel 文件
【发布时间】:2013-03-03 18:37:50
【问题描述】:

我已经成功创建并保存了一个 excel 文件:

// Rename the file
$fileName = URL . "MODEL/case" . $caseNO . ".xlsx";

// Write the file
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, $fileType);
$objWriter->save($fileName);

我想现在 PHPExcel 自动运行 Excel,打开创建的文件并将其最大化。 可能吗?即使 Excel 已经在运行,这也能工作吗?

感谢您的帮助,

多纳托

【问题讨论】:

  • 我认为这是不可能的。保存后你的excel文件是被动的。而且您的 php 文件无法访问用户的计算机,也无法控制。那将是一场灾难!
  • 你唯一能做的就是弹出一个下载框而不是简单的保存...为此你需要设置标题
  • 您好,swampnes,请原谅我提出的无聊问题。你能再解释一下吗?
  • @user1956370 我在下面的答案中提到的大部分内容......如果有疑问请告诉我

标签: php phpexcel


【解决方案1】:

根据我上面的评论,您只能强制拥有一个下载选项。为此,您可以通过这种方式设置标题 -

header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
header("Content-Disposition: attachment;filename=\"filename.xlsx\"");
header("Cache-Control: max-age=0");

参考 - PHP Excel Reader

有关更多选项,您还可以查看备忘单 - Cheat Sheet

虽然在这里阅读的最佳方式 - Codeplex

编辑

做这样的事情-

$excel = new PHPExcel();
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="your_name.xls"');
header('Cache-Control: max-age=0');  

// Do your stuff here

$writer = PHPExcel_IOFactory::createWriter($excel, 'Excel5');  

// This line will force the file to download    
$writer->save('php://output');

【讨论】:

  • 原谅我 swapesh,你写的代码是 javascript 正确的吗?当你说它会强制下载时,你的意思是它会打开文件吗?
  • @user1956370 这些是 PHP 标头 .. 不需要宽恕 kina 的话.. 如果你不知道我知道也没关系,但还有很多其他事情你肯定知道,但我不知道 @987654324 @
  • @user1956370 使用这个 $objWriter->save('php://output');
  • 当使用$objWriter->save('php://output');在共享主机中,我收到一个奇怪的错误。有什么线索吗?未捕获的异常“PHPExcel_Writer_Exception”,带有消息“无法打开 php://output 进行写入。”在third_party/PHPExcel/Writer/Excel2007.php:241 堆栈跟踪:#0
  • @Enrique 你可能对此感兴趣stackoverflow.com/a/21440309/639406
【解决方案2】:

PHPExcel 无法在客户端上运行 MS Excel....但您可以将文件直接下载到浏览器,这将为客户端提供将其保存到磁盘或直接在 MS Excel 中打开它的选项(如果他们有MS Excel 安装)通过发送适当的 http 标头,并将文件“保存”到 php://output。

当然,如果客户端没有安装 MS Excel,则不能在 MS Excel 中打开;虽然它仍然会提示保存。

/Tests 或 /Examples 目录中的 01simple-download-xlsx.php 文件正是这样做的

“是的”,如果 MS Excel 已经在客户端上运行,它将起作用

【讨论】:

  • 如果没有你,Stackoverflow 会在 PHPExcel 上做什么?
【解决方案3】:

在创建 Writer 之前插入以下标题

$filename = "filedetail". date("Y-m-d-H-i-s").".xlsx";
header('Content-Type: application/vnd.ms-excel'); 
header('Content-Disposition: attachment;filename="'.$filename.'"');
header('Cache-Control: max-age=0'); 
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');

【讨论】:

    【解决方案4】:
    header("Location: ".URL . "MODEL/case" . $caseNO . ".xlsx");
    

    【讨论】:

    • 请不要简单地发布代码。提供有关您的代码的一些解释或信息或用法。例如,请参阅this answer。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-02
    • 1970-01-01
    • 2015-02-16
    • 1970-01-01
    • 1970-01-01
    • 2015-05-15
    相关资源
    最近更新 更多