I am working with PhpSpreadsheet. When I use a formula that copies cell values, it adds to the formula the # symbol. This cause constant an error.
I need to prevent PhpSpreadsheet from adding this # symbol.
When I remove the #, the formula works perfectly.
//** Create a new Spreadsheet Object **//
$spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
$worksheet = $spreadsheet->getActiveSheet(); //get current active sheet (first sheet)
//** Set and load the reader **//
$inputFileName = $basePath;
$reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx(); // Create a new Reader of type xlsx
$reader->setReadDataOnly(false); // Keeping the style
$spreadsheet = $reader->load($inputFileName); // Load $inputFileName to a Spreadsheet Object
$spreadsheet->getActiveSheet()->fromArray($ufields, null, 'A8', true);
$attrs = $spreadsheet->getActiveSheet()->getCell("A10")->getFormulaAttributes();
$attrs['t'] = 'array';
$spreadsheet->getActiveSheet()->getCell("A10")->setFormulaAttributes($attrs);
$spreadsheet->getActiveSheet()->setCellValue("A10",'=IF(all_details!A8:I8<>"", all_details!A8:I8, "")');
$writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
$writer->setPreCalculateFormulas(false);
$writer->save($inputFileName);
//Export sheet code
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="'.$reportOriginalname.'"');
header('Cache-Control: max-age=0');
** I read and tried the solution suggested here, but it didn't work for me.
Related
I'm currently trying to export a list of products (from an API, around 6000 products) to an .xlsx file where I list the product name and its thumbnail.
For text values everything is fine, but I'm trying to render the image directly in the spreadsheet, using PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing.
My issue is after a certain amount of generated image, my process runs out of memory.
Here's my code:
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->getColumnDimension('B')->setAutoSize(true);
$sheet->getColumnDimension('C')->setAutoSize(true);
foreach ($products as $k => $product) {
$sheet->setCellValueByColumnAndRow(1, $k+1, $product['ref']);
$sheet->getCellByColumnAndRow(1, $k+1)->setDataType(DataType::TYPE_STRING);
$sheet->setCellValueByColumnAndRow(2, $k+1, $product['title']);
if (empty($product['image'])) {
continue;
}
$drawing = new MemoryDrawing();
$sheet->getRowDimension($k+1)->setRowHeight(80);
$gdImage = substr_count($imagePath, '.png') ? imagecreatefrompng($imagePath) : imagecreatefromjpeg($imagePath);
$drawing->setName('Thumbnail');
$drawing->setDescription('Thumbnail');
$drawing->setResizeProportional(true);
$drawing->setImageResource($gdImage);
$drawing->setRenderingFunction(substr_count($imagePath, '.png') ? MemoryDrawing::RENDERING_PNG : MemoryDrawing::RENDERING_JPEG);
$drawing->setMimeType(MemoryDrawing::MIMETYPE_DEFAULT);
$drawing->setHeight(80);
$drawing->setOffsetX(0);
$drawing->setOffsetY(0);
$drawing->setCoordinates('C'.($k+1));
$drawing->setWorksheet($sheet);
unset($drawing);
}
$writer = new Xlsx($spreadsheet);
$writer->save($filePath);
I've also tried to write my file, unset the spreadsheet and reload it every 100 or 200 lines, but I'm losing all the memory images written before.
if ($k % 100 === 0) {
$writer = new Xlsx($spreadsheet);
$writer->save($filePath);
$spreadsheet->disconnectWorksheets();
$spreadsheet->garbageCollect();
unset($spreadsheet);
unset($sheet);
$reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
$spreadsheet = $reader->load($filePath);
$sheet = $spreadsheet->getActiveSheet();
}
Is there any way to make it work?
try this (persist result in the file system and not in memory)
$drawing->setWorksheet($spreadsheet->getActiveSheet());
$writer = new Xlsx($spreadsheet);
$writer->save('my_file.xlsx');
I want to automatically generate new excel file if i run this code:
//file.php
$arrtweet[] = array(....);
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$objPHPExcel = $objReader->load("file/ABCDay-1.xlsx");
$objSheet = $objPHPExcel->getActiveSheet();
$objSheet->setTitle('Data ABC Day-1');
$objSheet->getCell('A1')->setValue('User_ID');
$objSheet->getCell('C1')->setValue('Content');
$objSheet->getCell('D1')->setValue('Timestamp');
$objPHPExcel->getActiveSheet()->fromArray($arrtweet, NULL, 'A2');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel,"Excel2007");
$objWriter->save("file/ABCDay-1.xlsx");
What I want is:
PHP will automatically generate new excel file if I run that codes for day-2,day-3...,day-N
. Is that possible? Can you help me? thank you so much :')
I'm losing time as hell using this PHPExcel lib.
My code is widely inspired from models which are available in the lib.
+The mission is :
-To read an *.xls file with PHP
-Display it in a navigator in HTML
For the moment, I just can read the file successfully (with a "createReader" method of PHPExcel_IOFactory instance). But for the HTML display, I'm in a pretty good crap. At attempt of code correction gives me this error:
" Fatal error: Uncaught exception 'PHPExcel_Calculation_Exception' with
message 'Réalisé S03!P374 -> Réalisé S03!P374 -> Formula Error:
Unexpected ,' "
Here is the code :
<?phperror_reporting(E_ALL);
set_time_limit(0);
date_default_timezone_set('Europe/London');
/** Include path **/
set_include_path(get_include_path() . PATH_SEPARATOR . '../../../Classes/');
/** PHPExcel_IOFactory */
include 'PHPExcel/IOFactory.php';
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>PHPExcel Reader Example #02</title>
</head>
<body>
<h1>Chargement fichier Facturation</h1>
<?php
$inputFileName = '../Docs_PDC/FACTURATION_Janvier.xls';
echo 'Loading file ',pathinfo($inputFileName,PATHINFO_BASENAME),' using PHPExcel_Reader_Excel5<br />';
$objReader = new PHPExcel_Reader_Excel5();
// $objReader = new PHPExcel_Reader_Excel2007();
// $objReader = new PHPExcel_Reader_Excel2003XML();
// $objReader = new PHPExcel_Reader_OOCalc();
// $objReader = new PHPExcel_Reader_SYLK();
// $objReader = new PHPExcel_Reader_Gnumeric();
// $objReader = new PHPExcel_Reader_CSV();
$objPHPExcel = $objReader->load($inputFileName);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'HTML');
$objWriter->save('Facturation.html');
echo '<hr />';
$sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
var_dump($sheetData);
$filename = "DownloadReport";
$table = $_POST['table'];
// save $table inside temporary file that will be deleted later
$tmpfile = tempnam(sys_get_temp_dir(), 'html');
file_put_contents($tmpfile, $table);
// insert $table into $objPHPExcel's Active Sheet through $excelHTMLReader
$objPHPExcel = new PHPExcel();
$excelHTMLReader = PHPExcel_IOFactory::createReader('HTML');
$excelHTMLReader->loadIntoExisting($tmpfile, $objPHPExcel);
$objPHPExcel->getActiveSheet()->setTitle('Facturation'); // Change sheet's title if you want
unlink($tmpfile); // delete temporary file because it isn't needed anymore
header('Content-Type: application/vnd.openxmlformats- officedocument.spreadsheetml.sheet'); // header for .xlxs file
header('Content-Disposition: attachment;filename='.$filename); // specify the download file name
exit;
?>
<body>
If someone has any idea I'll eternally grateful to him (or her ;) )
I dug a little more on this, and i noticed that: the exception is raised because
PHPExcel tries to resolve a formula with an Excel reference value (like "P$7") in argument. And the referenced value is not a number, it's just a column name.
So, Is it possible to disable PHPExcel's formula solving in some fields ? Or is there any other way to get around this ?
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