what function to update the formulas of the excel file? - spreadsheet

with what function to update the formulas of the excel file?
if I modify the value of cell C2 and C3, the formula of cell C4 which is equal to sum C2: C3 does not update
what is missing in my code so that the calculation is regenerated?
in my source file I have a lot of complex formulas that I would like to be updated automatically after changing the value of some cells
thank you
?php
session_start();
header('Content-Type: text/html; charset=UTF-8'); /*obligatoire sur chaque page*/
//call the autoload
require 'PhpSpreadSheet/vendor/autoload.php';
//include the classes needed to create and write .xlsx file
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Reader\IReader;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
//create directly an object instance of the IOFactory class, and load the xlsx file
$fxls ='excel-file_1.xlsx';
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($fxls);
//read excel data and store it into an array
$xls_data1 = $spreadsheet->getActiveSheet()->getCell('C2');
$xls_data2 = $spreadsheet->getActiveSheet()->getCell('C3');
$xls_data3 = $spreadsheet->getActiveSheet()->getCell('C4')->getCalculatedValue();
echo $xls_data1.' | '.$xls_data2.' | '.$xls_data3;
//result: 4000 | 15000 | 19000 => it's ok! C4=C2+C3
echo '<br/>';
$spreadsheet->getActiveSheet()->setCellValue('C2', '5000');
$spreadsheet->getActiveSheet()->setCellValue('C3', '17896');
$xls_data4 = $spreadsheet->getActiveSheet()->getCell('C2');
$xls_data5 = $spreadsheet->getActiveSheet()->getCell('C3');
$xls_data6 = $spreadsheet->getActiveSheet()->getCell('C4')->getCalculatedValue();
echo $xls_data4.' | '.$xls_data5.' | '.$xls_data6;
//result: 5000 | 17896 | 19000 => it's not good => not 19000 but 22896 (C4=C2+C3)
?>

I found a tip to solve my problem but another problem arises
the saved file cannot be modified (read only).
do you know a solution so that the saved file can remain editable?
please
thank you
<?php
session_start();
header('Content-Type: text/html; charset=UTF-8');
require 'PhpSpreadSheet/vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Reader\IReader;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
$fxls ='file.xls';
$spreadsheet = PhpOffice\PhpSpreadsheet\IOFactory::load($fxls);
$spreadsheet->getActiveSheet()->setCellValue('H4', '5'); $spreadsheet->getActiveSheet()->setCellValue('I4', '0');
$spreadsheet->getActiveSheet()->setCellValue('H5', '2'); $spreadsheet->getActiveSheet()->setCellValue('I5', '1');
$spreadsheet->getActiveSheet()->setCellValue('H6', '3'); $spreadsheet->getActiveSheet()->setCellValue('I6', '3');
$writer = PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, "Xlsx");
$writer->save($fxls); (file read only?)
$spreadsheet = PhpOffice\PhpSpreadsheet\IOFactory::load($fxls);
//$xls_data4 = $spreadsheet->getActiveSheet()->getCell('C8');
//$xls_data5 = $spreadsheet->getActiveSheet()->getCell('Z8');
$xls_data1 = $spreadsheet->getActiveSheet()->getCell('V8')->getCalculatedValue();
$xls_data2 = $spreadsheet->getActiveSheet()->getCell('Z8')->getCalculatedValue();
echo $xls_data1.'<br/>';
echo $xls_data2.'<br/>';
?>

Related

PhpSpreadsheet's and PHP 7 > ZipArchive::close failure to create tempory file

At work, we use PhpSpreadsheet to generate some Excel file (we use it to be able to provide some export).
Here is the simple code I use (based on some example given but PhpSpreadsheet) to generate a file:
<?php
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
include_once '../../../libs/includes.inc';
/** #var array $_POST */
$_POST = db::encodeHTMLPost($_POST);
/** #var string $httpReferer */
$httpReferer = $_SERVER['HTTP_REFERER'];
if (strstr($httpReferer, '?')) {
$httpReferer = explode('?', $httpReferer);
$httpReferer = $httpReferer[0];
}
try {
/** #var Spreadsheet $spreadsheet */
$spreadsheet = new Spreadsheet();
//$spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
// Set the document properties
$spreadsheet
->getProperties()
->setCreator('Christina')
->setLastModifiedBy('Christina')
->setTitle('Test XLSX')
->setSubject('Here is the test')
->setDescription('Test document for Office 2007 XLSX, generated using PHP classes.')
->setKeywords('office 2007 openxml php')
->setCategory('Test result file');
$spreadsheet->setActiveSheetIndex(0)
->setCellValue('A1', 'Hello')
->setCellValue('B2', 'World')
->setCellValue('C1', 'Here')
->setCellValue('D2', 'test');
$spreadsheet->getActiveSheet()->setTitle('A simple test');
$spreadsheet->setActiveSheetIndex(0);
// Redirect output to a client’s web browser (Xlsx)
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="01simple.xlsx"');
header('Cache-Control: max-age=0');
// If you're serving to IE 9, then the following may be needed
header('Cache-Control: max-age=1');
// If you're serving to IE over SSL, then the following may be needed
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
header('Pragma: public'); // HTTP/1.0
$writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
$writer->save('php://output');
exit;
} catch (Exception $e) {
var_dump($e);
}
Unfortunately, it returns an error in the generate Excel file:
Warning: ZipArchive::close(): Failure to create temporary file: No such file or directory in /Applications/XAMPP/xamppfiles/htdocs/bdoparticipantenweekend.nl/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx.php on line 409
I understand the error, I just don't know how to fix it.
I'm the only one to have this error at the office, of course.. I'm the only one to use PHP 7
I made some research, apparently PHP 7 as another behaviour about Zip::close(): https://www.php.net/manual/en/ziparchive.close.php#119960
Is somebody have a clue how to fix this ?
NB: PhpSpreadsheet is update at the version 1.8.2 (the latest one)
Your path is wrong or you have not the permission to write into the path. Change the destination path or the permissions.

Magento2 read uploaded csv file

I have upload CSV file but problem is i don't know how to read data of uploaded csv file in Magento2.
Please help me anyone.
Thanks in advance.
You can do that like you could in Magento 1. In Magento 1 you would use
new Varien_File_Csvbut in Magento 2 you can do the same with \Magento\Framework\File\Csv. You can use the following code.
In your __construct() inject the following classes:
protected $_fileCsv;
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Framework\Module\Dir\Reader $moduleReader,
\Magento\Framework\File\Csv $fileCsv
) {
$this->_moduleReader = $moduleReader;
$this->_fileCsv = $fileCsv;
parent::__construct($context); // If your class doesn't have a parent, you don't need to do this, of course.
}
Then you can use it like this:
// This is the directory where you put your CSV file.
$directory = $this->_moduleReader->getModuleDir('etc', 'Vendor_Modulename');
// This is your CSV file.
$file = $directory . '/your_csv_file_name.csv';
if (file_exists($file)) {
$data = $this->_fileCsv->getData($file);
// This skips the first line of your csv file, since it will probably be a heading. Set $i = 0 to not skip the first line.
for($i=1; $i<count($data); $i++) {
var_dump($data[$i]); // $data[$i] is an array with your csv columns as values.
}
}

PHPEXCEL download with PDO database error text become symbol

I am using sample exel code and add using PDO to add data export excel
if (PHP_SAPI == 'cli')
die('This example should only be run from a Web Browser');
/** Include PHPExcel */
require_once dirname(__FILE__) . '/Classes/PHPExcel.php';
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
i am edit some properties
// Set document properties
$objPHPExcel->getProperties()->setCreator("Team IT KSP PRIMADANA")
->setLastModifiedBy("Team IT KSP PRIMADANA")
->setTitle("DATA NASABAH")
->setSubject("KSP PRIMADANA")
->setDescription("Data Perusahaan.")
->setKeywords("office 2007 openxml php")
->setCategory("Penting");
i am also add some data for header excel, until this code, when try download is okay an not error.
// Add some data
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', 'Tanggal Masuk')
->setCellValue('B1', 'Nomor Register')
->setCellValue('C1', 'Cabang');
then when add looping PDO to add data content table and download it, value from this database make symbol data excel
$host = 'localhost';
$username = 'root';
$password = 'server';
$dbname = 'primadana';
// Create your database query
this is my PDO for print data from database to excel which make text to symbol
try{
$conn = new PDO("mysql:host=$host;dbname=$dbname",$username,$password);
//$stmt = $conn->prepare('select * from tblpdo where age=:age');
$stmt = $conn->prepare('SELECT * FROM data_berkas_masuk where user_id = 6 order by user_id');
$result=$stmt->fetchAll();
$no=2;
if(count($result))
{
foreach ($result as $row) {
$objPHPExcel->getActiveSheet()->SetCellValue('A'.$no, ($row['in_tgl']));
$no++;
}
}
else{echo "no rows returned";}
}
catch(PDOException $e){
echo 'ERROR: '.$e->getMessage();
}
// Rename worksheet
$objPHPExcel->getActiveSheet()->setTitle('Simple');
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);
// Redirect output to a client’s web browser (Excel5)
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="01simple.xls"');
header('Cache-Control: max-age=0');
// If you're serving to IE 9, then the following may be needed
header('Cache-Control: max-age=1');
// If you're serving to IE over SSL, then the following may be needed
header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
header ('Pragma: public'); // HTTP/1.0
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
exit;
?>
i find myself lol.
$stmt = $conn->prepare('SELECT * FROM data_berkas_masuk where user_id = 6 order by user_id');
$stmt->execute();
$result=$stmt;

Create a zip file from a list of selected files and make the zipped file downloadable in Drupal 7

I have a list of image files. I need to archive those files in zip format and make the archived file downloadable. I have seen ArchiverZip class defined in the system module of Drupal 7. But I couldn't be able to create a zip file. How can I do this in Drupal 7 ? Is there any hooks or custom modules for this ? Please help me out with this.
UPDATED
Following are the codes:
$zip = new ArchiverZip('archive.zip');
foreach($_POST['img'] as $fid):
$query = db_select('file_managed', 'fn')
->condition('fid', $fid)
->fields('fn', array('filename'));
$result = $query->execute();
foreach($result as $row) {
if(file_exists('sites/default/files/'.$row->filename)){
var_dump($zip->add($base_path.'sites/default/files/'.$row->filename));
}
}
endforeach;
And this reflects the following error
Exception: Cannot open archive.zip in ArchiverZip->__construct() (line 91 of basepath\modules\system\system.archiver.inc).
Please help me with this . .
Well I missed to create the archive.zip file before creating the ArchiverZip class so the archiving operation failed previously . . Now the code will be like below:
$filename = 'archive.zip';
fopen($filename, 'w');
$zip = new ArchiverZip($filename);
foreach($_POST['img'] as $fid):
$query = db_select('file_managed', 'fn')
->condition('fid', $fid)
->fields('fn', array('filename'));
$result = $query->execute();
foreach($result as $row) {
if(file_exists('sites/default/files/'.$row->filename)){
$zip->add($base_path.'sites/default/files/'.$row->filename);
}
}
endforeach;

How to do mysql_fetch_array in Magento

I want to create a drop down option using Magento module that populate the data from the database I created.
Previously, I have this code in My IndexController.php which is work. This is the first code.
public function dropdownAction() {
if (file_exists('./app/etc/local.xml')) {
$xml = simplexml_load_file('./app/etc/local.xml');
$tblprefix = $xml->global->resources->db->table_prefix;
$dbhost = $xml->global->resources->default_setup->connection->host;
$dbuser = $xml->global->resources->default_setup->connection->username;
$dbpass = $xml->global->resources->default_setup->connection->password;
$dbname = $xml->global->resources->default_setup->connection->dbname;
}
else {
exit('Failed to open ./app/etc/local.xml');
}
$link = mysql_connect($dbhost,$dbuser,$dbpass);
mysql_select_db($dbname) or die("Unable to select database");
$tblname = $tblprefix.'my_db_table';
$result = mysql_query("SELECT dropdowndata FROM ".$tblname."");
echo '<select>';
while ($ary = mysql_fetch_array($result)){
echo "<option>" . $ary['dropdowndata '] . "</option>";
}
echo "</select>";
mysql_close($link);
}
But I think the code above is not the Magento way. Do you agree?
Now, I want to populate the data with this code in IndexController.php. This is the second code.
public function dropdownAction() {
$options= Mage::getModel('my/model')->getCollection();
foreach($options as $option){
$optionData = $option->getDropdowndata ();
echo "<select>";
echo "<option>" .$optionData."</option>";
echo "</select>";
}
}
Using the code above, the data was populated but one data with one drop down option. So there are so many drop down options appear on the browser, each drop down option will contain only one data.
I think I am missing the while ($ary = mysql_fetch_array($result)). But I confuse how to include that code?
So, my question is how to do mysql_fetch_array in Magento? Or can somebody please explain how to make the second code above work like the first code.
getData() function returns an array of the whole data, and of course need move 'select' nodes out of the foreach
echo "<select>";
foreach($options as $option){
$optionData = $option->getData();
echo "<option>" .$optionData['somekey'] ."</option>";
}
echo "</select>";
But I think would be better use the magento magic functions, for example if you have 'entity_id' column in DB you can get value using $option->getEntityId(), etc...
And why do you have select inside of foreach? I think something like this will solve your problem:
public function dropdownAction() {
$options= Mage::getModel('my/model')->getCollection();
echo "<select>";
foreach($options as $option){
$optionData = $option->getDropdowndata ();
echo "<option>" .$optionData."</option>";
}
echo "</select>";
}