使用标头加载和保存PHPExcel模板

时间:2018-03-26 18:18:05

标签: templates phpexcel

我使用PHPExcel用Excel从Excel描述模板然后输出它。

问题是我想将文件保存在桌面上,但我不知道如何定义桌面路径?

我还想将“标题”集成到文件中,以便显示保存对话框。 但是,如果我加载模板,这不起作用,因为我收到错误消息:“文件类型不适合”。

这是我现有的代码:

// Start
define('EOL',(PHP_SAPI == 'cli') ? PHP_EOL : '<br />');

// Include Class
require_once dirname(__FILE__) . '/Classes/PHPExcel.php';

// Template loading
$objPHPExcel = PHPExcel_IOFactory::load('Template.xlsx');

// Define Values
$test = 'Test';

$objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('B5', $test)                 
            ;


// Excel Document save 
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('C:\Users\ ???  \Desktop\Data.xlsx');

感谢您的帮助

2 个答案:

答案 0 :(得分:0)

你遗漏了一些事情,你需要指定fileType和一个对象createReader来传递给load

// Start
define('EOL',(PHP_SAPI == 'cli') ? PHP_EOL : '<br />');

// Include Class
require_once dirname(__FILE__) . '/Classes/PHPExcel.php';

// Template loading
$fileType = 'Excel2007'; // use 'Excel5' for .xls files
$fileName = 'Template.xlsx';

$objReader = PHPExcel_IOFactory::createReader($fileType);
$objPHPExcel = $objReader->load($fileName);

// Define Values
$test = 'Test';

$objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('B5', $test)                 
            ;


// Excel Document save with header
$xlsName = 'Document';          
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
//header('Content-Type: application/vnd.ms-excel'); // use the header below instead ( for xlsx files )
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); 

header('Content-Disposition: attachment;filename='.$xlsName.''); // quotes are removed here
header('Cache-Control: max-age=0');
$objWriter->save('php://output');

选中保存对话框:bring up save as dialog within php

答案 1 :(得分:0)

好的,我已经更换了代码。但是使用标题它不起作用,因为我收到了不兼容的文件类型的消息。行为准则是​​:

// Start
define('EOL',(PHP_SAPI == 'cli') ? PHP_EOL : '<br />');

// Include Class
require_once dirname(__FILE__) . '/Classes/PHPExcel.php';

// Template loading
$fileType = 'Excel2007'; // use 'Excel5' for .xls files
$fileName = 'Template.xlsx';

$objReader = PHPExcel_IOFactory::createReader($fileType);
$objPHPExcel = $objReader->load($fileName);

// Define Values
$test = 'Test';

$objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('B5', $test)                 
            ;


// Excel Document save with header
$xlsName = 'Document';          
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="'.$xlsName.'"');
header('Cache-Control: max-age=0');
$objWriter->save('php://output');