OLE AUTOMATION WITH PHP or PHP-CLI? - php

I read here http://www.daniweb.com/code/snippet217293.html# it is possible.
What should be activated in PHP.Ini or elsewhere to make this work ? Are there any examples with Excel ?

If you are running php on windows it will be installed by default. There are a few options you can set though. I don't believe they're needed:
http://www.php.net/manual/en/com.configuration.php
As for an example working with excel? Here's a little snippet I found for pulling out a value from an excel spreadsheet:
<?PHP
$filename = "c:/spreadhseet/test.xls";
$sheet1 = 1;
$sheet2 = "sheet2";
$excel_app = new COM("Excel.application") or Die ("Did not connect");
print "Application name: {$excel_app->Application->value}\n" ;
print "Loaded version: {$excel_app->Application->version}\n";
$Workbook = $excel_app->Workbooks->Open("$filename") or Die("Did not open $filename $Workbook");
$Worksheet = $Workbook->Worksheets($sheet1);
$Worksheet->activate;
$excel_cell = $Worksheet->Range("C4");
$excel_cell->activate;
$excel_result = $excel_cell->value;
print "$excel_result\n";
$Worksheet = $Workbook->Worksheets($sheet2);
$Worksheet->activate;
$excel_cell = $Worksheet->Range("C4");
$excel_cell->activate;
$excel_result = $excel_cell->value;
print "$excel_result\n";
#To close all instances of excel:
$Workbook->Close;
unset($Worksheet);
unset($Workbook);
$excel_app->Workbooks->Close();
$excel_app->Quit();
unset($excel_app);
?>

what's your target? Import excel into a DB? You can use PHPExcelReader or dbTube.org
for this task. Here you are.
PHP is platform independend. I think it is not a good idea to break this....in
a long term of view.
greeting
NotALinuxMan

Related

Style & layout is not copied while creating new pptx from pptx in PHPPresentation

I want to split slides of one pptx file into seperated pptx files, containing one slide each. The content/text is copied but the layout & styling is not copied. Here is the code.
Can anyone please help ?
<?php
use PhpOffice\PhpPresentation\PhpPresentation;
use PhpOffice\PhpPresentation\IOFactory;
use PhpOffice\PhpPresentation\Style\Color;
use PhpOffice\PhpPresentation\Style\Alignment;
use PhpOffice\PhpPresentation\Slide\SlideLayout;
$objReader = \PhpOffice\PhpPresentation\IOFactory::createReader('PowerPoint2007');
$objPHPPowerPoint = $objReader->load('a.pptx');
$totalSlides = $objPHPPowerPoint->getSlideCount();
$oMasterSlide = $objPHPPowerPoint->getAllMasterSlides()[0];
$documentProperties = $objPHPPowerPoint->getDocumentProperties();
for ( $count = 0; $count < $totalSlides; $count++ ) {
$objPHPPresentation = new PhpPresentation();
$slide = $objPHPPowerPoint->getSlide( $count );
$background = $slide->getBackground();
$newSlide = $objPHPPresentation->addSlide( $slide );
$newSlide->setBackground ( $background );
$objPHPPresentation->setAllMasterSlides( $oMasterSlide );
$objPHPPresentation->removeSlideByIndex(0);
$oWriterPPTX = \PhpOffice\PhpPresentation\IOFactory::createWriter($objPHPPresentation, 'PowerPoint2007');
$oWriterPPTX->save($count.'.pptx');
}
I don't think it's an issue with your code - more an issue with the underlying libraries - as mentioned here: PhpPresentation imagecreatefromstring(): Data is not in a recognized format - PHP7.2
It ran a test to see if it was something I could replicate - and I was able to. The key difference in my test was in one presentation I had a simple background, and in the other it was a gradient.
This slide caused problems:
But this one was copied over fine:
With the more complex background I got errors like:
PHP Warning: imagecreatefromstring(): Data is not in a recognized format
My code is even less complicated than yours, I just clone the original slideshow and remove all except a single slide before saving it:
for ( $count = 0; $count < $totalSlides; $count++ ) {
$copyVersion = clone $objPHPPowerPoint;
foreach ($copyVersion->getAllSlides() as $index => $slide) {
if ($index !== $count) {
$copyVersion->removeSlideByIndex($index);
}
}
$oWriterPPTX = \PhpOffice\PhpPresentation\IOFactory::createWriter($copyVersion, 'PowerPoint2007');
$oWriterPPTX->save($count.'.pptx');
}
Sorry if this doesn't exactly solve your problem, but hopefully it can help identify why it's happening. The other answer I linked to has more information about finding unsupported images types in your slides.
You can try using Aspose.Slides Cloud SDK for PHP to split a presentation into separate slides and save them to many formats. You can evaluate this REST-based API making 150 free API calls per month for API learning and presentation processing. The following code example shows you how to split a presentation and save slides to PPTX format using Aspose.Slides Cloud:
use Aspose\Slides\Cloud\Sdk\Api\Configuration;
use Aspose\Slides\Cloud\Sdk\Api\SlidesApi;
use Aspose\Slides\Cloud\Sdk\Model;
$configuration = new Configuration();
$configuration->setAppSid("my_client_id");
$configuration->setAppKey("my_client_key");
$slidesApi = new SlidesApi(null, $configuration);
$filePath = "example.pptx";
// Upload the file to the default storage.
$fileStream = fopen($filePath, 'r');
$slidesApi->uploadFile($filePath, $fileStream);
// Split the file and save the slides in PPTX format in the same folder.
$response = $slidesApi->split($filePath, null, Model\SlideExportFormat::PPTX);
// Download files of the slides.
foreach($response->getSlides() as $slide) {
$slideFilePath = pathinfo($slide->getHref())["basename"];
$slideFile = $slidesApi->downloadFile($slideFilePath);
echo $slideFile->getRealPath(), "\r\n";
}
Sometimes it is necessary to split a presentation without using any code. In this case, you can use Online PowerPoint Splitter.
I work as a Support Developer at Aspose.

Removing sheet from Excel 2005 using PHP

I want to delete sheets from an Excel2005/Excel5 file using PHP. I am using PHPExcel-1.7.9. I am using the following code to delete Excel2007 files as follows
$exceltype="Excel2007";
$excel = PHPExcel_IOFactory::createReader($exceltype);
$excel = $excel->load("ABC.xlsx");
$count = $excel->getSheetCount();
for($i = 0; $i < $count; $i++)
{
$excel->removeSheetByIndex(0);
}
When I use it for Excel5, I get an error
Fatal error: Call to undefined method PHPExcel_Reader_Excel5::getSheetCount()
Potential Issue #1
Use a different variable name for the Reader and for the object that you're loading from the Reader
$exceltype="Excel2007";
$excelReader = PHPExcel_IOFactory::createReader($exceltype);
$excel = $excelReader->load("ABC.xlsx");
Potential Issue #2
It's always sensible to let PHPExcel identify the filetype for you rather than trusting to the file extension
$excel = PHPExcel_IOFactory::load("ABC.xlsx");
Documentation

Populate Excel Range using COM object in php

I would like to speed up excel generation on server using range. I know hot to populate 1 cell one by one.
For instance:
$ExcelApp = new COM("excel.application") or die("Unable to start MS Excel");
$ExcelWordbook = $ExcelApp->Workbooks->Add();
$ExcelSheet = $ExcelWordbook->Worksheets(1);
$ExcelSheet->Activate;
$ExcelSheet->Cells(1, 1)->value = "id";
$ExcelSheet->Cells(1, 2)->value = "user";
$ExcelSheet->Cells(1, 3)->value = "pn";
But How to make it in one shot using range? Something like this of course is not working.
$ExcelSheet->Range("A1:A3")->value = array("id","user","pn");
Any idea? Thanks
Have you try with phpexcel framework its a excellent framework

How to update csv column names with database table header

I am facing this problem some past days and now frustrate because I have to do it.
I need to update my CSV file columns name with database table header. My database table fields are different from CSV file. Now the problem is that first I want to update column name of CSV file with database table headers and then import its data with field mapping into database.
Please help me I don't know how I can solve this.
This is my php code:
$file = $_POST['fileName'];
$filename = "../files/" . $file;
$list = $_POST['str'];
$array_imp = implode(',', $list);
$array_exp = explode(',', $array_imp);
$fp = fopen("../files/" . $file, "w");
$num = count($fp);
for ($c = 0; $c < $num; $c++) {
if ($fp[c] !== '') {
fputcsv($fp, $array_exp);
}
}
fclose($fp);
require_once("../csv/DataSource.php");
$path = "../files/test_mysql.csv";
$dbtable = $ext[0];
$csv = new File_CSV_DataSource;
$csv->load($path);
$csvData = $csv->connect();
$res='';
foreach($csvData as $key)
{ print_r($key[1]);
$myKey ='';
$myVal='';
foreach($key as $k=>$v)
{
$myKey .=$k.',';
$myVal .="'".$v."',";
}
$myKey = substr($myKey, 0, -1);
$myVal = substr($myVal, 0, -1);
$query="insert into tablename($myKey)values($myVal)";
$res= mysql_query($query);
You have got an existing file of which the first line needs to be replaced.
This has been generally outlined here:
Overwrite Line in File with PHP
Some little explanation (and some tips that are not covered in the other question). Most often it's easier to operate with two files here:
The existing file (to be copied from)
A new file that temporarily will be used to write into.
When done, the old file will be deleted and the new file will be renamed to the name of the old file.
Your code does not work because you are already writing the new first line into the old file. That will chop-off the rest of the file when you close it.
Also you look misguided about some basic PHP features, e.g. using count on a file-handle does not help you to get the number of lines. It will just return 1.
Here is step by step what you need to do:
Open the existing file to read from. Just read the first line of it to advance the file-pointer (fgets)
Open a new file to write into. Write the new headers into it (as you already successfully do).
Copy all remaining data from the first file into the new, second file. PHP has a function for that, it is called stream_copy_to_stream.
Close both files.
Now check if the new file is what you're looking for. When this all works, you need to add some more steps:
Rename the original file to a new name. This can be done with rename.
Rename the file you've been written to to the original filename.
If you want, you then can delete the file you renamed in 5. - but only if you don't need it any longer.
And that's it. I hope this is helpful. The PHP manual contains example code for all the functions mentioned and linked. Good luck. And if you don't understand your own code, use the manual to read about it first. That reduces the places where you can introduce errors.
If you are managing to insert the table headers then you're half way there.
It sounds to me like you need to append the data after the headers something like:
$data = $headers;
if($fp[c]!=='')
{
$data .= fputcsv($fp, $array_exp);
}
Notice the dot '.' before the equals '=' in the if statement. This will add none blank $fp[c]values after the headers.

Convert .shp files to an excel spreadsheet programmatically

I have a file in .shp format and I need it to convert it to an Excel spreadsheet programmatically. I want to do this using PHP or JavaScript.
Once I've used small PHP lib ShapeFile, you can get it in phpclasses.org. Although it is a bit of not so good design, it works.
Here is a little example from my own code:
require_once 'lib/ShapeFile.inc.php';
$shp = new ShapeFile($filename, array('noparts' => false));
if ($shp->getError() !== '')
print_r($shp->getError());
else
{
$records = array();
while ($record = $shp->getNext())
{
$dbf_data = $record->getDbfData();
$shp_data = $record->getShpData();
//Dump the information
$obj = array(
'type' => $shp->getShpTypeName($record->getShpType())
);
$obj['shape'] = $shp_data;
$obj['meta'] = $dbf_data;
$records[] = $obj;
}
}
print_r($records);
So, after that $records contain all the data from shapefile. Of course, you will need some time to figure out what shapefile is and what data it can hold (assuming you are not familiar with it). Start from wikipedia. Actually there are bunch of arrays with some labels.
Then use some php excel lib (just seek in so) and you're done :)

Categories