I try to make a PhpSpreadsheet document and after that add him in a mail attachement. Maybe is the heat but after some hours in phpSpreadsheet documentation i haven't found anything.
Here my file for send mail
$name = 'export-sst';
$filename = FileAssociatedPeer::getNewTempFilename($name . '.xlsx"');
$filepath = sfConfig::get('sf_upload_dir') . sfConfig::get('app_sfPropelFileAssocPlugin_temp_dir') . '/' . $filename;
include dirname(__FILE__) . 'template.php';
$mail = new PHPMailerBootstrap();
$mail->initialize();
$mail->setCharset('utf-8');
$mail->setContentType('text/html');
$mail->setMailer('smtp');
$mail->setPort((int) sfConfig::get('app_send_mail_port'));
$mail->setHostname(sfConfig::get('app_send_mail_host'));
$mail->setUsername(sfConfig::get('app_send_mail_username'));
$mail->setPassword(sfConfig::get('app_send_mail_password'));
$mail->setSender('cyril#quarks.pro');
$mail->setFrom('cyril#quarks.pro', 'Logiciel Quarks');
$subject = 'test';
$mail->setSubject($subject);
$body = <<<EOT
Test
EOT;
$mail->setBody(nl2br($body));
$mail->addAddress('test#talala.com');
$mail->addAttachment($spreadsheet, $name . '.xlsx', 'base64', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
$mail->send();
Here my SpreadSheet construction after looking documentation.
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Style;
use PhpOffice\PhpSpreadsheet\Style\Conditional;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use PhpOffice\PhpSpreadsheet\Worksheet\Drawing;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\IOFactory;
$spreadsheet = new Spreadsheet();
$active_sheet = $spreadsheet->getActiveSheet();
$active_sheet->setTitle('Tableau général');
$active_sheet->setCellValue('A1', 'Hello World !');
$active_sheet->setCellValue('B1', 'tada');
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="'. $filename .'.xlsx"');
header('Cache-Control: max-age=0');
$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save('php://output');
I have no problem for sending mail without addAttachement but when i uncomment this line all my tries throw errors.
Thank for your time
Best Regards
The couldn't close zip file error indicates that you have not the right permissions for the target file path.
Try to use the absolut path to be sure you have the right path.
$path = "<Absolut Path>";
//do stuff
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save($path);
Related
i want to download a file of projet but i get it empty. i'am using a spreadsheet librairy
Notice : i a make a dump after save function , my file is full and not empty in the path directory of project
Someone can help me !
bellow is my code :
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load('template.xlsx');
$worksheet = $spreadsheet->getActiveSheet();
$filename = 'write.xls';
$worksheet->getCell('A1')->setValue('John');
$worksheet->getCell('A2')->setValue('Smith');
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xls');
$writer->save($filename); die;
// to download file
header('Content-Type: application/vnd.ms-excel');
header("Content-Length:".filesize($filename));
header("Content-Disposition: attachment;filename=$filename");
header('Cache-Control: max-age=0');
$writer->save('php://output');
exit();
i except a full file after downloading it
This function would work:
define ("ONE_DAY", 86400);
function getExisting()
{
$rootFolder = "pathTodirectory";
//first clear old files
$files = scandir($rootFolder,1);
array_pop($files); array_pop($files);
foreach($files as $file)
{
$fp = $rootFolder . DIRECTORY_SEPARATOR . $file;
$filemtime=filemtime($fp);
if (time() - $filemtime >= (2 * ONE_DAY))unlink($fp);
}//end clearing old files
//second rescan folder for current files
$files = scandir($rootFolder,1);
array_pop($files); array_pop($files);
$existing = array_reverse($files);
return $existing;
}
$existing = getExisting();
echo "\n<p> Select file or enter office number to review inventory:";
echo "\n <ul>";
foreach($existing as $rpt)
{
$spd = "pathTodirectory" . $rpt; \\make sure to follow up with relative path name here also
echo "\n <li><a href=\"$spd\" >" . $rpt ."</a></li>";
}
echo "\n </ul>";
I think it is the load() usage issue, your code works with following correction in my site :
$file_loc = 'template.xlsx';
$file_type = \PhpOffice\PhpSpreadsheet\IOFactory::identify($file_loc);
$reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($file_type);
// $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load('template.xlsx');
$spreadsheet = $reader->load($file_loc);
$worksheet = $spreadsheet->getActiveSheet();
$filename = 'write.xls';
$worksheet->getCell('A1')->setValue('John');
$worksheet->getCell('A2')->setValue('Smith');
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xls');
// save a physical file in server, you can skip this actually
$writer->save($target_dir . $filename);
// die; // don't die, be happy (^_^)
// to download file
header('Content-Type: application/vnd.ms-excel');
header("Content-Length:" . filesize($filename));
header("Content-Disposition: attachment;filename=$filename");
header('Cache-Control: max-age=0');
$writer->save('php://output');
exit();
I need to generate an excel file (xls) and trigger the download after it is generated.
I found this example in the documentation.
<?php
require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', 'Hello World !');
$writer = new Xlsx($spreadsheet);
$writer->save('hello world.xlsx');
It shows how to create a excel file and save it on the server.
How can I serve the result to the client instead and "force" him to download it?
I need to get the data of the $writer somehow.
I am currently solving it without PhpSpreadsheet:
// Excel Export
$filename = 'export_'.date('d-m-y').'.xls';
$filename = $validator->removeWhitespace($filename);
header('Content-type: application/ms-excel');
header('Content-Disposition: attachment; filename='.$filename);
exit($response["output"]); // <-- contains excel file content
But it is not working with my delimiter (semicolon). The semicolon is not getting interpreted and everything is getting written into one column.
If I export it as .csv, then it works. But I need it as .xls or .xlsx
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
class DownloadExcel
{
public static function createExcel(array $data, array $headers = [],
$fileName = 'data.xlsx')
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
for ($i = 0, $l = sizeof($headers); $i < $l; $i++) {
$sheet->setCellValueByColumnAndRow($i + 1, 1, $headers[$i]);
}
for ($i = 0, $l = sizeof($data); $i < $l; $i++) { // row $i
$j = 0;
foreach ($data[$i] as $k => $v) { // column $j
$sheet->setCellValueByColumnAndRow($j + 1, ($i + 1 + 1), $v);
$j++;
}
}
$writer = new Xlsx($spreadsheet);
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment; filename="'. urlencode($fileName).'"');
$writer->save('php://output');
}
}
This is what I use to create a spreadsheet with PhpSpreadsheet and output directly to php://output for download.
I had the same problem and found a solution here : https://github.com/PHPOffice/PhpSpreadsheet/issues/217
I ended my method with $writer->save('php://output'); then exit()
My answer :
PHP:
$writer = new Xlsx($spreadsheet);
ob_start();
$writer->save('php://output');
$ret['data'] = base64_encode(ob_get_contents());
ob_end_clean();
JS:
var linkSource = 'data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,'+ response.data ;
var downloadLink = document.createElement("a");
var fileName = 'clients.' + format;
downloadLink.href = linkSource;
downloadLink.download = fileName;
downloadLink.click();
I solved it with a workaround. I temporarily save the file on the server, then I load the content into a variable and serve it as a download file. Then I delete the file from the server.
Workaround:
$date = date('d-m-y-'.substr((string)microtime(), 1, 8));
$date = str_replace(".", "", $date);
$filename = "export_".$date.".xlsx";
try {
$writer = new Xlsx($response["spreadsheet"]);
$writer->save($filename);
$content = file_get_contents($filename);
} catch(Exception $e) {
exit($e->getMessage());
}
header("Content-Disposition: attachment; filename=".$filename);
unlink($filename);
exit($content);
call ob_end_clean(); just before the $writer->save('php://output').
ob_end_clean();
$writer->save('php://output');
This worked for me:
$excel = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
$sheet = $excel->getActiveSheet();
$sheet->setTitle('This is a test', true);
ob_end_clean();
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="filename_' . time() . '.xlsx"');
header('Cache-Control: max-age=0');
$xlsxWriter = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($excel, 'Xlsx');
$xlsxWriter = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($excel);
exit($xlsxWriter->save('php://output'));
If you have problems where the files download corrupted, it is always good to check if there is any extra whitespace at the top of your file output. If your PHP files have blank white lines, whilst HTML won't have a problem, your phpspreadsheet file will. Spent a good chunk of time trying to fix these issues but the problem was with the whitespace!
I am in searching to find a solution to convert the .xlsx(Excel) file into pdf files.
require_once('phpExcel/PHPExcel/IOFactory.php');
require_once('phpexcel/PHPExcel.php');
$fileType = 'Excel5';
$fileName = 'testing.xlsx';
$outputFileType = 'PDF';
$outputFileName = 'test.pdf';
$objPHPExcel = PHPExcel_IOFactory::load($fileName);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, $outputFileType);
$objWriter->writeAllSheets();
$objWriter->save($outputFileName);
I used this above code,but is not working. If any can an Idea, please help me
I've been looking everywhere on how to do this with two existing files, looks like all documentation is on creating new files. I'd like to take one of the files and add the second file to it as a new worksheet then save it to the server.
I've been trying with no avail like this:
$file="test.xls";
$file2="test2.xls";
$outputFile = "final.xls";
$phpExcel = new PHPExcel($file);
$phpExcel->getActiveSheet();
$phpExcel->setActiveSheetIndex(0);
$phpExcel->addSheet($file2);
header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=$outputFile");
header("Cache-Control: max-age=0");
$objWriter = PHPExcel_IOFactory::createWriter($phpExcel, "Excel5");
file_put_contents($outputFile, $objWriter);
Any help would be greatly appreciated. Very new to PHP.
Doesn't anybody ever read documentation these days? There's a whole document in the folder called /Documentation about reading files to PHPExcel objects (it's called PHPExcel User Documentation - Reading Spreadsheet Files), together with dozens of examples (the /Documentation/Examples/Reader folder is a good place to look), and none of them use new PHPExcel($file). Nor do any of the examples or any of the documents say to use file_put_contents() when saving.
$file1="test.xls";
$file2="test2.xls";
$outputFile = "final.xls";
// Files are loaded to PHPExcel using the IOFactory load() method
$objPHPExcel1 = PHPExcel_IOFactory::load($file1);
$objPHPExcel2 = PHPExcel_IOFactory::load($file2);
// Copy worksheets from $objPHPExcel2 to $objPHPExcel1
foreach($objPHPExcel2->getAllSheets() as $sheet) {
$objPHPExcel1->addExternalSheet($sheet)
}
// Save $objPHPExcel1 to browser as an .xls file
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel1, "Excel5");
header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=$outputFile");
header("Cache-Control: max-age=0");
$objWriter->save('php://output');
// update from office site
$filenames = array('doc1.xlsx', 'doc2.xlsx');
$bigExcel = new PHPExcel();
$bigExcel->removeSheetByIndex(0);
$reader = PHPExcel_IOFactory::createReader($input_file_type);
foreach ($filenames as $filename) {
$excel = $reader->load($filename);
foreach ($excel->getAllSheets() as $sheet) {
$bigExcel->addExternalSheet($sheet);
}
foreach ($excel->getNamedRanges() as $namedRange) {
$bigExcel->addNamedRange($namedRange);
}
}
$writer = PHPExcel_IOFactory::createWriter($bigExcel, 'Excel5');
$file_creation_date = date("Y-m-d");
// name of file, which needs to be attached during email sending
$saving_name = "Report_Name" . $file_creation_date . '.xls';
// save file at some random location
$writer->save($file_path_location . $saving_name);
// More Detail : with different object:
Merge multiple xls file into single one is explained here:
I'm going to describe a bit different:
http://rosevinod.wordpress.com/2014/03/15/combine-two-or-more-xls-files-as-worksheets-phpexcel/
// Combine all .csv files into one .xls file,
$cache_dir = "/home/user_name/public_html/";
$book1 = $cache_dir . "book1.csv";
$book2 = $cache_dir . "book2.csv";
$outputFile = $cache_dir . "combined.xls";
$inputFileType = 'CSV';
$inputFileNames = array($book1,$book2);
$objReader = new PHPExcel_Reader_CSV();
/** Extract the first named file from the array list **/
$inputFileName = array_shift($inputFileNames);
/** Load the initial file to the first worksheet in a PHPExcel Object **/
$objPHPExcel = $objReader->load($inputFileName);
/** Set the worksheet title (to the filename that we've loaded) **/
$objPHPExcel->getActiveSheet()
->setTitle(pathinfo($inputFileName,PATHINFO_BASENAME));
/** Loop through all the remaining files in the list **/
foreach($inputFileNames as $sheet => $inputFileName) {
/** Increment the worksheet index pointer for the Reader **/
$objReader->setSheetIndex($sheet+1);
/** Load the current file into a new worksheet in PHPExcel **/
$objReader->loadIntoExisting($inputFileName,$objPHPExcel);
/** Set the worksheet title (to the filename that we've loaded) **/
$objPHPExcel->getActiveSheet()->setTitle(pathinfo($inputFileName,PATHINFO_BASENAME));
}
$objWriter = new PHPExcel_Writer_Excel5($objPHPExcel);
$objWriter->save( $outputFile );
$objPHPExcel->disconnectWorksheets();
unset($objPHPExcel);
echo "DONE";
this is my code i want to attach this file and send it and the values are numerical variables that in excel file i use them to drow a chart
it dosen't work at all ,
my boss is mad at me , Help
let me explain more . i have to attach an excel file {which contains 4 numbers that are a test result and draw a chart } I've done the test i have the result, i have done sending with attachment but i can't make the file .
require_once '../Classes/PHPExcel.php';
$fileType = 'Excel2007';
$fileName = 'Result.xlsx';
// Read the file
$objReader = PHPExcel_IOFactory::createReader($fileType);
$objPHPExcel = $objReader->load($fileName);
// Change the file
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, $fileType);
$objSheet = $objPHPExcel->setActiveSheetIndex(0);
objSheet->getCell('A2')->setValue($SumY );
objSheet->getCell('B2')->setValue($SumR );
objSheet->getCell('C2')->setValue($SumB );
objSheet->getCell('D2')->setValue($SumG );
// Write the file
$objWriter->save('Result.xlsx');
Tell PHPExcel that you want to include charts when reading and writing
Assuming that the chart is defined in your template
require_once '../Classes/PHPExcel.php';
$fileType = 'Excel2007';
$fileName = 'Result.xlsx';
// Read the file (including chart template)
$objReader = PHPExcel_IOFactory::createReader($fileType);
$objReader->setIncludeCharts(TRUE);
$objPHPExcel = $objReader->load($fileName);
// Change the file
$objSheet = $objPHPExcel->setActiveSheetIndex(0);
$objSheet->getCell('A2')->setValue($SumY );
$objSheet->getCell('B2')->setValue($SumR );
$objSheet->getCell('C2')->setValue($SumB );
$objSheet->getCell('D2')->setValue($SumG );
// Write the file (including chart)
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, $fileType);
$objWriter->setIncludeCharts(TRUE);
$objWriter->save('Result.xlsx');
If the chart isn't defined in your template, then you need to create it in your code