Writing into Excel file using PhpSpreadsheet - php

I have a php code that is triggered whenever a user clicks a determined button. That code basically creates a new directory and a new Excel File inside that same dir. My goal is to write into that excel file. I have the following code (which is not working, btw):
$filename = 'moldes/VLMOLDES_'.$id.'/Orcamento161.xlsm';
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($filename);
$worksheet = $spreadsheet->getActiveSheet();
$worksheet->getCell('A18')->setValue('3');
Everything but writing in the file is working as expected. When I click the button, it opens a blank page but nothing happens! I've tried a lot of different ways but I'm a noob in phpSpreadSheets. How can I write in a specific cell in that file?

You're missing the following - you need to save the file at the end of your code or the changes won't be reflected in the file.
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, "Xlsx");
$writer->save('moldes/VLMOLDES_'.$id.'/Orcamento161.xlsm');
Also, it may be preferred to use:
$worksheet->setCellValue('A18', '3');

Related

Copy charts from (.xls or .xlsx) using PHP

I am working on a template excel file for some projects and my goal is to populate it with PHP. I create an excel document with two sheets, one is a table with all of the information that I am going to plot, and the second sheet is just a graph that is based on the table from the previous sheet.
Whenever I use (https://github.com/PHPOffice/PhpSpreadsheet) PHPSpreadsheet (since PHPExcel is deprecated) I am able to read/write/copy/etc the first sheet, but whenever I try to save the sheet without touching the graph sheet at all, nothing happens. I save the file successfully but when I try to open it I get an error stating that Excel found unreadable content in the file and to repair it. I repair it and the second sheet with the graph is empty.
https://github.com/PHPOffice/PhpSpreadsheet/issues/382
This is the closest thing I found to my issue, and I did add the setIncludeChart functions, but nothing seems to work.
I also feel that I have exhausted online searches and am now hoping that there is an alternative to PHPSpreadsheet that will allow me to use a chart in a template (supplied) excel file.
$xls = 'KPI_ReadinessTemplate.xls';
$xlsxTarget = 'NEWX_KPI_ReadinessTemplate.xlsx';
$xlsTarget = 'NEW_KPI_ReadinessTemplate.xls';
$inputFileType = 'Xlsx';
$inputFileName = $xlsx;
$reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
$reader->setIncludeCharts(true);
$spreadsheet = $reader->load($inputFileName);
$worksheet = $spreadsheet->getActiveSheet();
$worksheet->getCell('A1')->setValue('Help me');
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->setIncludeCharts(true);
$fileData = $writer->save($xlsxTarget);
$reader = new \PhpOffice\PhpSpreadsheet\Reader\Xls();
$reader->setIncludeCharts(TRUE);
$workbook = $reader->load($xls);
$writer = new \PhpOffice\PhpSpreadsheet\Writer\Xls($workbook);
$writer->setIncludeCharts(TRUE);
$writer->save($xlsTarget);
I am expecting the chart to be copied, in the code from above there is no modification of the file, it should be an exact one-to-one copy of the supplied file but it isn't working at all as it seems the graph gets corrupted and I have to repair the excel the next time I open it.
EDIT: I also installed the archived PHPExcel and tried it using Graph disapear read and write excel file using PHPExcel and I still had the same issue.

Only save changes in PHPExcel

I am using PHPExcel for editing a large XLSX file (~230kb, 20 sheets). They way I do it yet is:
load the file (create the PHPExcel object)
do the changes on the PHPExcel object
overwrite the XLSX file with a new one
This is very slow (~6 seconds), although there are only small changes (some cells in just one worksheet).
Is there a way to save just the changes in the file? Or if not, with another library?
You can try to do it with Spout: https://github.com/box/spout. It should not take more than a second and your code should look like this:
$reader = ReaderFactory::create(Type::XLSX);
$reader->open('path/to/file/to/read.xlsx');
$writer = WriterFactory::create(Type::XLSX);
$writer->openToFile('path/to/file/to/write.xlsx'); // needs to be different than the one read for now
while ($reader->hasNextSheet()) {
$reader->nextSheet();
while ($reader->hasNextRow()) {
$row = $reader->nextRow();
// change the row here if needed
$writer->addRow($row);
}
}
$reader->close();
$writer->close();
// And at the end, you can replace the old file with the new one:
rename('path/to/file/to/read.xlsx', 'path/to/file/to/write.xlsx');
Hope that helps!

How to update Excel data? (Refresh all queries)

I have a Excel xlsm file with a few queries.
Currently I open it every day and click on the "Refresh All" command in the "Data" tab. I want this to be done automatically. I wrote a script in python (I'm a newbie in Python).
The problem is that after the data is refreshed and the Excel file has been saved, the refreshed data is not visible (I know that refreshing works because if I prevent to save and close the Excel file, the refreshed data is visible in the file )
The weird thing is that saving also works fine because when I try to modify cell B2 from 'config' it is changed...
Where is the problem?
import win32com.client
import datetime
from datetime import date, timedelta
yesterday = date.today() - timedelta(1)
office = win32com.client.Dispatch("Excel.Application")
wb = office.Workbooks.Open(r'\\server\CC_source.xlsm')
office.DisplayAlerts = True
office.Visible = True
wb.RefreshAll()
sh = wb.Worksheets("config")
sh.Cells(2,2).Value = wczoraj
wb.Close(True)
Maybe someone can recommend another script? For example, Powershell? PHP?
Or an other library for Python3?
Since you requested another script to perform this action, I recommend PowerShell. As a simple test, I created an Excel document, SheetToRefresh.xlsx, which has a data connection to a simple xml file. However, the script below will work for any data source that the Excel document is connected to. I have tested this on my own machine, the data refresh and save persists, as expected.
RefreshExcel.ps1
#Set the file path (can be a network location)
$filePath = "C:\Scripts\SheetToRefresh.xlsx"
#Create the Excel Object
$excelObj = New-Object -ComObject Excel.Application
#Make Excel visible. Set to $false if you want this done in the background
$excelObj.Visible = $true
#Open the workbook
$workBook = $excelObj.Workbooks.Open($filePath)
#Focus on the top row of the "Data" worksheet
#Note: This is only for visibility, it does not affect the data refresh
$workSheet = $workBook.Sheets.Item("Data")
$workSheet.Select()
#Refresh all data in this workbook
$workBook.RefreshAll()
#Save any changes done by the refresh
$workBook.Save()
#Uncomment this line if you want Excel to close on its own
#$excelObj.Quit()
To refresh your query then your pivot, in Excel go to data> queries and connections> right click query for query properties> uncheck the enable background refresh.

How to modify excel file using PHPExcel in symfony2

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);

Error in generated pdf file using zend_pdf under Magento

I'm trying to create a PDF file, under a Magento phtml file, this is my code :
$pdf = new Zend_Pdf();
$pdf->pages[] = $pdf->newPage(Zend_Pdf_Page::SIZE_A4);
$page=$pdf->pages[0]; // this will get reference to the first page.
$style = new Zend_Pdf_Style();
$style->setLineColor(new Zend_Pdf_Color_Rgb(0,0,0));
$font = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_TIMES);
$style->setFont($font,12);
$page->setStyle($style);
$page->drawText('example text here',100,($page->getHeight()-100));
$pdf->render();
$pdf->save('test.pdf','true');
My PDF file is created, but I can't open it with acrobat reader.
When I open it with a text editor and compare it with another simple pdf files, I noticed that in the first line was missing in my generated pdf file. it contains "%PDF-1.4"
How can I add this line programmatically with zend_pdf in my pdf file ?
Thanks for help.
According to the zend manual the second save parameter is only for updating files that already exist. In this case you are creating a new file so don't use that option.
$pdf->save('test.pdf');
PS. This answer is technically an RTM statement.

Categories