I have an .XLS file with macros I have to modify and keep the macros and images it contains. I can open the file and modify the cell data but it loses the macros and images. I tried to search for the problem on Google but I only found solutions for .xlsm files. I hope it's possible to keep the macros in an .xls file too. Here is my code for the opening and saving:
include_once libraries_get_path('PHPExcel').'/PHPExcel.php';
include_once libraries_get_path('PHPExcel').'/PHPExcel/IOFactory.php';
$template = PHPExcel_IOFactory::load('private://xls/form_template.xls');
$template->setActiveSheetIndex(0);
// Modifying the cells data here...
$objWriter = PHPExcel_IOFactory::createWriter($template, 'Excel5');
$objWriter->save('sites/default/files/'.$filename);
It's a really important function in the project and the customer needs it ASAP.
Related
I have code for converting xls to xlsx via PHPExcel:
$objPHPexcel = PHPExcel_IOFactory::load('file.xlsx');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPexcel, 'Excel5');
$objWriter->save('new_file.xls');
But when I open created xls file some cells are empty.
What could be the problem?
Thanks!
Link to download original xlsx file
you should use one of following as formate type.
1)Excel5 -> file format between Excel Version 95 to 2003
2)Excel2003XML -> file format for Excel 2003
3)Excel2007 -> file format for Excel 2007
and add following line at line no.3 in your code before save file statement.
$fileType=PHPExcel_IOFactory::identify("file.xlsx"); //We can get file reader type automatically using
it generate file as per your requirement.
I do notice that some of these cells contain references to external files, e.g. cell A23 contains
='[Форма 1-2 от 15.12 ЯНВАРЬ екат.xls]НТТЗМ'!A77
Logically, PHPExcel can't simply access that external file (Форма 1-2 от 15.12 ЯНВАРЬ екат.xls) to retrieve data; nor can it handle references to external files... the file may not even exist; and if it did, there is a major overhead in loading (recursively) every external file that might be referenced in formulae.
While you haven't indicated which cells might be blank in the newly saved file, it would be my guess that they're the cells that contain these external file references
I am using PHPExcel to read and write values to Excel. I have a template that has a graph and a style on it.
Here's the issue:
After I appended some value on the Excel sheet, the style of the chart has been remove and it shows the default style.
I am using this code to read:
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
// Tell the reader to include charts when it loads a file
$objReader->setIncludeCharts(TRUE);
// Load the file
$objPHPExcel = $objReader->load("rcca.xlsx");
And this to write
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->setIncludeCharts(TRUE);
$objWriter->save('rcca.xlsx');
Am I missing something?
Please see the screenshot of the chart style before and after:
Had the same problems with charts using PHPExcel
(my main problem was to change colors of chart bars)
First of all if some one did not know or forgot xlsx files are zip archs
So the main problem is that PHPExcel when saving xlsx file adds default theme file xl/theme/theme1.xml even if you change it at $objReader->load file it will overwrite it to default at $objWriter->save.
Charts colors in that file theme1.xml at <a:accent1> (...2,3,4,5,6)
so i took theme1.xml changed colors to which i need, saved and using The ZipArchive class overwrite it after
$objWriter->save with simple code
$zip = new ZipArchive;
if ($zip->open('filename.xlsx') === TRUE) {
$zip->addFile('mytheme1.xml', 'xl/theme/theme1.xml');
$zip->close();
echo 'ok';
} else {
echo 'err';
}
I hope it will help someone
It seems that chart styling need to be hard-coded at this time.
On this other thread someone explain how to add some styling PHPExcel graph design (border, graph color, graph inner position)
In my project I use symfony2 PHPExcel wrapper https://github.com/liuggio/ExcelBundle
With the example from the link above I can create new excel files. However this file has no style or markup at all. So I created a excel template where I want to input some data.
I know how to load an excel file:
$excelObj = $this->get('xls.load_xls2007')
->load($this->get('kernel')
->getRootDir() . '/../web/excel-template.xlsx');
//custom modifications on excel file
Now I need to create a response. But in the doc of ExcelBundle there is no information on how to do that. They just show how response work for a excel file that is created by code.
I tried:
$excelService->setExcelObj($excelObj);
$response = $excelService->getResponse();
//the rest is equal to the code in the doc
but it gives me a blank excel document.
Any ideas how to make a response with a loaded excel file?
you can do this by
// Read the file
$objReader = PHPExcel_IOFactory::createReader($fileType);
$objPHPExcel = $objReader->load($fileName);
// Change the file
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', 'Hello')
->setCellValue('B1', 'World!');
// Write the file
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, $fileType);
$objWriter->save($fileName);
if you dont understand please comment..
I would save the file to disk and redirect the user to the on-disk version personally. This will allow several things
Your web server to serve files instead of PHP, a good thing from a performance and memory usage standpoint.
Decouple your architecture a bit to allow for future changes such as moving the creation and loading of Excel files to asynchronous operations.
The ability to use http://wiki.nginx.org/XSendfile (There is an Apache module also).
The user can re-download the file or pause and resume download without recreating it.
To do this you will want to
Save the file to a web accessible temp directory after its created
Redirect the user to that file location
Create a cron or some other job that deletes older files in the temp directory.
The tempfile api (http://us2.php.net/tmpfile) might be useful here.
the new version 2.* of PHPExcelbundle could help you.
Is now possible:
//read
$phpExcelObject = $this->get('phpexcel')->createPHPExcelObject('file.xls');
$phpExcelObject->setActiveSheetIndex(0)
->setCellValue( 'C6', 'some text' )
->setCellValue( 'D6', 'some text2' );
$writer = $this->get('phpexcel')->createWriter($phpExcelObject, 'Excel5');
$writer->save('file.xls');
// or
$response = $this->get('phpexcel')->createStreamedResponse($writer);
I have tried to use phpexcel with my own template file. phpexcel loads the file and writes data to some cells A2, A3, A4 for example.. and opens an output file with the new data.
my template file has chart built-in.. all i want to phpexcel to do is to populate values in cells and don't touch the chart. And, open the new file. (Please note that I don't want to make the chart in code.. I want the chart to pre-exist with in my template in same format as I created originally). Only the data should update.
But, when i try to do this.. the chart itself goes missing from the resulting file. After trying various ways.. still failed.
And, i found the following code from http://phpexcel.codeplex.com/discussions/397263
require_once 'Classes/PHPExcel.php';
/** PHPExcel_IOFactory */
include 'Classes/PHPExcel/IOFactory.php';
$target ='Results/';
$fileType = 'Excel2007';
$InputFileName = $target.'Result.xlsx';
$OutputFileName = $target . '_Result.xlsx';
//Read the file (including chart template)
$objReader = PHPExcel_IOFactory::createReader($fileType);
$objReader->setIncludeCharts(TRUE);
$objPHPExcel = $objReader->load($InputFileName);
//Change the file
$objPHPExcel->setActiveSheetIndex(0)
// Add data
->setCellValue('C3','10' )
->setCellValue('C4','20' )
->setCellValue('C5','30')
->setCellValue('C5','40' );
//Write the file (including chart)
PHPExcel_Settings::setZipClass(PHPExcel_Settings::PCLZIP);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, $fileType);
$objWriter->setIncludeCharts(TRUE);
$objWriter->save($OutputFileName);
The above code works in excel 2010 and now keeps my chart in tact... but still when I try to use filetype "Excel5" it doesn't work.
It throws the following error:
Fatal error: Call to undefined method PHPExcel_Reader_Excel5::setIncludeCharts()
in D:\IT\bfstools\PHPExcel\MyExamples\test1.php on line 16
Please provide a simple solution where I want my template file to work with .xls and .xlsx and all my original chart in the template file should stay intact. I do not want the chart removed it from the resulting file. Neither do I plan to create the chart using phpexcel code. (why write unnecessary code when excel can do all the work for you).
I want the easiest way out which is just to use everything with in my template and just populate cells with new data. And, my existing chart in the template comes live automatically. I don't want to write unnecessary code while I can safely rely on excel template and charting functions.
Please help.
There's a very good reason for this:
Charting is only implemented in core, and for the Excel2007 Readers and Writers at this point in time, so all of the other readers or writers will ignore charts, treat them as though they simply don't exist. The intention is to roll out charting to the other readers/writers over the coming year.
EDIT
I see from your comment that you don't understand how PHPExcel works at all, so I have a lot of explaining to do.
PHPExcel is not a library for "editing" workbook files: you're not using PHPExcel to change a file, you're changing a PHPExcel object that can be loaded from a file, and can subsequently be written to a file.
PHPExcel Core is an in-memory representation of the spreadsheet, with the different constituent objects such as worksheets, cells, images, styles, etc all represented as PHP Objects.
The PHPExcel Readers parse a spreadsheet file and load all the components from a file that they have been programmed to recognise, and create the appropriate PHPExcel core objects from those file components. If there is no equivalent PHPExcel Core object (such as Pivot Tables), then that file component can't be "loaded"; if the loader hasn't been programmed to recognise a file component, then it can't be loaded. In these cases, those elements from the file are simply ignored. Once the Reader has done it's job, a PHPExcel object exists, and the spreadsheet file is closed and forgotten.
When a PHPExcel Core object exists in memory, you have a set of methods allowing you to manipulate and change it, to add, modify or delete Core elements; but these work purely on the "in memory" collection of worksheet, cell, style objects that comprise the PHPExcel Core. The Core exists without knowledge of having been loaded from a file or having been created using a PHP "new PHPExcel()" statement; it makes no changes to files in any way.
When writing, the reverse is true. Each Writer takes the PHPExcel core objects, and writes them to a file in the appropriate format (Excel BIFF, OfficeOpenXML, HTML, etc). Like the Readers, each writer can only write those PHPExcel Core objects that it has been programmed to write. If it has not been programmed to write (for example, charts) then any charts defined in the PHPExcel Core will be ignored because that writer simply doesn't know how to write them yet. Likewise, features that exist in PHPExcel Core that are not supported by the file format that is being written to (such as cell styles for the CSV Writer) are ignored.
So to support a spreadsheet feature such as charts, it is necessary for the PHPExcel Core object collection to have been modified to provide an "in memory" representation of those elements, and for the different Readers to have been programmed to recognise those elements in the file they are loading and to convert them to the appropriate PHPExcel Core objects, and for the different Writers to have been programmed to convert the PHPExcel core representation to the appropriate file representation.
Each Reader and each Writer needs to be programmed individually. Charts is a relatively new feature, only added to the PHPExcel Core in the 1.7.7 release, and at this point only the Reader and Writer for the Excel2007 format have been programmed to recognise chart elements.
While it is the intention of the developers to extend this to cover the other formats as well, the necessary code isn't created automagically. Programming each individual Reader and Writer takes time and effort. While the Chart code for the Excel2007 Reader and Writer has now stabilised to the point where it is now no longer considered "experimental", and development focus is turning to writing the necessary code for chart handling in the Excel5 Reader and Writer, it is work that has not yet been completed.
If you can use Golang, try Excelize. Support save file without losing original charts of XLSX.
Try set setIncludeCharts
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
// Tell the reader to include charts when it loads a file
$objReader->setIncludeCharts(TRUE);
// Load the file
$objPHPExcel = $objReader->load($filePath);
I know this isn't the right place to ask about this specific vague problem, but maybe someone knows this library well enough to enlighten me. Here is the thing:
I am writting an Excel5 over an existing Excel file with PHPExcel. I need to upload that Excel to the Zoom website, so it can provide me with a list of tracking numbers. However, for some reason the library they are using to read the uploaded Excel files cannot read the rows written by PHPExcel and the only solution I've found so far is to manually copy the contents of my dynamically generated Excel to another document using MS Excel 2007.
In other words, the Zoom website can read the rows written natively by Excel but not rows written by PHPExcel. My file has only one single sheet, and I can open it no problem with Excel 2007.
Even if I manually add some rows to the template and then add more rows with PHPExcel, Zoom will read the rows written manually by me, but not the rows written by PHPExcel.
This is how I'm doing it:
// Starting with the PHPExcel library
$this->load->library('PHPExcel');
$this->load->library('PHPExcel/IOFactory');
$template_file = 'zoom_tracking_template.xls';
$i = 3;
$objReader = IOFactory::createReader('Excel5');
$objPHPExcel = $objReader->load($template_file);
$objPHPExcel->setActiveSheetIndex(0);
// Fetching ML payments
foreach($payments as $row)
{
$objPHPExcel->getActiveSheet()->setCellValue('A'.$i, 'VANESSA NEISZER');
$objPHPExcel->getActiveSheet()->setCellValue('B'.$i, '02127616116');
$objPHPExcel->getActiveSheet()->setCellValue('C'.$i, '1ER PISO MINITIENDAS 199 BLVD SABANA GRANDE, CRUCE C / CALLE NEGRIN');
$objPHPExcel->getActiveSheet()->setCellValue('D'.$i, $row->mailing_city);
$objPHPExcel->getActiveSheet()->setCellValue('E'.$i, $row->mailing_name);
$objPHPExcel->getActiveSheet()->setCellValue('F'.$i, $row->mailing_name);
$objPHPExcel->getActiveSheet()->setCellValue('G'.$i, $row->mailing_personal_id);
$objPHPExcel->getActiveSheet()->setCellValue('H'.$i, $row->mailing_phone);
$objPHPExcel->getActiveSheet()->setCellValue('I'.$i, $row->mailing_address1.' '.$row->mailing_address2);
$objPHPExcel->getActiveSheet()->setCellValue('J'.$i, $row->nickname);
$objPHPExcel->getActiveSheet()->setCellValue('K'.$i, '1');
$objPHPExcel->getActiveSheet()->setCellValue('L'.$i, '0.3');
$objPHPExcel->getActiveSheet()->setCellValue('M'.$i, 'M');
$objPHPExcel->getActiveSheet()->setCellValue('N'.$i, 'PRODUCTO');
$objPHPExcel->getActiveSheet()->setCellValue('O'.$i, '0');
$i++;
}
$objPHPExcel->setActiveSheetIndex(0);
$objWriter = IOFactory::createWriter($objPHPExcel, 'Excel5');
// Sending headers to force the user to download the file
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="Envios'.date('dMy').'.xls"');
header('Cache-Control: max-age=0');
$objWriter->save('php://output');
I have no clue of what PHP library they are using to read Excel files and I am certain they wont tell me if I ask them. I know they use PHP, and their library only read Excel 2003 files, however, I don't know why they can't read my files but they can read other files written manually on MS Excel.
Any clues, ideas or suggestions I could try would be greatly appreciated.
And PHPExcel's main developer is looking at this issue (among others), somewhere in between trying to find a new day job and having a life. I'm not familiar with the zoom website, or the software that they use. PHPExcel BIFF8 files can be read by Excel, OOCalc and Gnumeric without error... but a couple of questions spring to mind.
What version of PHPExcel?
Does any of the data contain UTF-8 characters?
Are there any formulae in the template worksheet?
If so, what are they?