Open an excel file using COM and save it as .xml file - php

Im trying the following code:
<?php
$workbook = "D:\b2\\test.XLS";
$sheet = "Sheet1";
#Instantiate the spreadsheet component.
$ex = new COM("Excel.sheet") or Die ("Did not connect");
#Get the application name and version
print "Application name:{$ex->Application->value}<BR>" ;
print "Loaded version: {$ex->Application->version}<BR>";
#Open the workbook that we want to use.
$wkb = $ex->application->Workbooks->Open($workbook) or Die ("Did not open");
#Create a copy of the workbook, so the original workbook will be preserved.
$ex->Application->ActiveWorkbook->SaveAs("D:\b2\Ourtest.xml");
#$ex->Application->Visible = 1; #Uncomment to make Excel visible.
#Optionally, save the modified workbook
$ex->Application->ActiveWorkbook->SaveAs("D:\Ourtest.xml");
#Close all workbooks without questioning
$ex->application->ActiveWorkbook->Close("False");
unset ($ex);
?>
This actually works and creates the Ourtest.xml file. But im getting characters like:
ÐÏࡱá > þÿ þÿÿÿ
I have tried with SaveAs("D:\Ourtest.pdf") and it says the file has been corrupted or incorrectly decoded.
Can anyone help me please?Thanks

That is because you are saving it as Excel Format. Check the Excel documentation for how to save it as an XML document - it might be a separate paramter to SaveAs or a different method alltogether (Export*).
EDIT: It seems SaveAs is the right method to use. Check the msdn documentation here. You probably want to specify the second parameter FileFormat. Maybe setting it to the XlFileFormat.xlXMLSpreadsheet value?

Problem solved by using
$ex->Application->ActiveWorkbook->SaveAs("D:\Ourtest.xml",46);
46 is the value for xlXMLSpreadsheet
Thanks everyone

Related

edit existing excel on web page using php

Does anyone have an idea to create the dynamic form with uploaded excel file.
We need to facilitate users to add data in the pre-uploaded file. Can anyone help with this? We are doing in this way:
$objPHPExcelWriter = PHPExcel_IOFactory::createWriter($objPHPExcel,'HTML');
$objPHPExcelWriter->save('php://output');
But this above code only displays structure of excel on the web still we're unable to edit it.
you will need 2 pear packages
PHP-ExcelReader package
Spreadsheet_Excel_Writer package
What you need to do is read first the excel file use PHP-ExcelReader package It reads the binary format of XLS files directly and can return values and formats from any cell. http://code.google.com/p/php-excel-reader/
read the excel file
$data = new Spreadsheet_Excel_Reader("test.xls");
show the data of the file
$data->dump($row_numbers=false,$col_letters=false,$sheet=0,$table_class='excel')
Once you have stored the data in a variable save the data in another file this time you will use the The Spreadsheet_Excel_Writer package https://github.com/pear/Spreadsheet_Excel_Writer
<?php
require_once 'Spreadsheet/Excel/Writer.php';
$workbook = new Spreadsheet_Excel_Writer('test.xls');
$worksheet =& $workbook->addWorksheet('My first worksheet');
if (PEAR::isError($worksheet)) {
die($worksheet->getMessage());
}
$workbook->close();
?>

Xlsx file, Read all spreadsheet in php

I am using simplexlsx to read xlsx sheet,
I have multiple tabs in my xlsx file, When I am trying to read data, its shows data only for first tab,
for better understanding i have attach print screen.
Try This,
$this->load->library('simplexlsx');
$xlsx = new SimpleXLSX( $file_path );
$data['csv_data'] = $xlsx->rows();
It is because when you select something from an excel file it performs that action with the active sheet which is by default is the first one.
You need to change that to the required sheet
Use the following code to do that
$objPHPExcel->setActiveSheetIndex($count); // Use no of the sheet you want to select -1 as count

How to refresh pivot table in excel using php

I have a file in xls format that I need to refresh (use 'refresh all' button in Excel) once a day and then retrieve the data from the pivot table and inset them into the database (MySQL). The file gets data from an external source (retrieve data from sharepoint 2007).
How is the easiest way to do this?
I'm thinking abaout PHP but do I not quite know how you go about it. From what I read PHPExcel does not support this operations.
When you try to use COM I get an error:
Fatal error: in D:\xampp\htdocs\sp\xls\index.php on line 11
And here is a php code:
<?php
// Start Excel
$excel = new COM("Excel.Application") or die ("Could not load Excel.Application");
// Make Excel visible.
$excel->Application->Visible = 1;
// Open workbook
$Workbook = $excel->Workbooks->Open('D:/xampp/htdocs/sp/xls/emails.xls', 'r+') ;
// Refresh all
$Workbook->RefreshAll();
// Save updated excel file out to disk somewhere
$Workbook->SaveAs('D:/xampp/htdocs/sp/xls/emails.xls');
// Close all instances of excel:
$Workbook->Close(false);
unset($Workbook);
$excel->Workbooks->Close();
$excel->Quit();
unset($excel);
?>
I'm using windows 7 and xampp with php 5.5.6
In php.ini I've added this line:
extension=php_com_dotnet.dll
Alternate: is it possible to run *.iqy file generated by sharepoint in php?
I found a workaround to my problem.
Instead, refresh the data by PHP pointed out in a query that collects data during the re-launch of the sheet. To this I added this VBA script save changes and close file.
At the end of the added task scheduler to run the sheet once per day.
The rest of downloading data from Excel using PHPExcel.

How to save a file from database to server in php

I have a database table to store my templates(.docx file). I am using openTbs to work on that templates.My need is that to take out the template and store it in thee server itself, and edit using openTbs.
My question is that how I can retrieve .docx file from database and store that in the server side.? (The storing may be temporary but i want to edit it using openTbs.)
Thanks in advance.......
It is bad practice to save binary data in the database, mostly when this data are intend to be processed by a file server, such as pictures or your DOCX.
Anyway, since OpenTBS 1.8.1, you can open an DOCX (or any Ms Office, LibreOffie or zip archive) from a PHP file handle.
You can use this feature to easily merge your template from the database :
// retrieve binary data of the file
$rs = mysql_query($dbc, "SELECT data FROM files WHERE id=$id");
$rec= mysql_fetch_array($rs, MYSQLI_ASSOC);
mysql_free($rs);
// create a temporary file
$temp = tmpfile();
fwrite($temp, $rec['file']);
unset($rec); // free PHP memory
// Open the file with OpenTBS
$TBS = new clsTinyButStrong;
$TBS->Plugin(TBS_INSTALL, OPENTBS_PLUGIN);
$TBS->LoadTemplate($temp);
...

PHPExcel dumping Excel contents onto Screen

I am using PHPExcel for the first time. I just wrote a basic code snippet to read one of my Excel files. I want to load the file, iterate through each row and process its contents. However, the function to load the file seems to dump its contents onto the screen.
My code snippet is this:
include 'lib/Classes/PHPExcel/IOFactory.php';
$dest = "uploads/";
$excel = "2012-12-STANDARD.xls";
$objPHPExcel = PHPExcel_IOFactory::load($dest.$excel);
On running this code, the data in the sheet has been echoed twice onto the screen. First, like a regular echo, and the second is a var_dump.
Here is a sample snippet of the screen output:
DOM ELEMENT: HTML DOM ELEMENT: BODY DOM ELEMENT: P START OF
PARAGRAPH: END OF PARAGRAPH: FLUSH CELL: A1 => Type ZipCode City
State County AreaCode CityType CityAliasAbbreviation CityAliasName
Latitude Longitude TimeZone Elevation CountyFIPS DayLightSaving
PreferredLastLineKey ClassificationCode MultiCounty StateFIPS
CityStateKey CityAliasCode PrimaryRecord CityMixedCase
CityAliasMixedCase StateANSI CountyANSI FacilityCode
CityDeliveryIndicator CarrierRouteRateSortation FinanceNumber
UniqueZIPName D 18540 ......
array 1 =>
array
'A' => string 'Type ZipCode City State County AreaCode CityType CityAliasAbbreviation CityAliasName Latitude Longitude TimeZone
Elevation CountyFIPS DayLightSaving PreferredLastLineKey
ClassificationCode MultiCounty StateFIPS CityStateKey CityAliasCode ........'... (length=4573)
Am I doing something wrong here? Why would the load function echo the contents before accessing it?
The cause of the problem is that the IOFactory static load method fails to determine your file's format correctly. You might not want to use it after all, because according to the documentation:
While easy to implement in your code, and you don't need to worry
about the file type; this isn't the most efficient method to load a
file; and it lacks the flexibility to configure the loader in any way
before actually reading the file into a PHPExcel object.
To successfully load the file you can instantiate a Reader explicitly specifying the format. For a file in Excel 2007 format it would be:
$xl_reader = PHPExcel_IOFactory::createReader('Excel2007');
$xl = $xl_reader->load("/tmp/yourfile.xls");
You can also use a Reader's canRead() method to determine wether the reader that you created can load the specified file.
$xl_reader = PHPExcel_IOFactory::createReader('Excel2007');
if ($xl_reader->canRead('/tmp/yourfile.xls')) {
echo "It's a success! Loading the file...";
$xl = $xl_reader->load('/tmp/yourfile.xls');
...
} else {
echo "Cannot read the file.";
...
}
That code is picking up on the HTML Reader, which still has some of my diagnostics in the code (mea culpa)... if you edit the file Classes/PHPExcel/Reader/HTML.php and comment out every line that contains an echo or a var_dump statement, then it should eliminate the problem.
Coincidence that it's something I was actually working on last night.
Then you can also ask the person who provided you with the file to give you a proper .xls file in future, rather than one which has an extension of .xls but contains html markup rather than a properly formatted BIFF file.
Try adding the PHPExcel to the PHP include path.
set_include_path(get_include_path().PATH_SEPARATOR.'lib/Classes/PHPExcel');
include 'lib/Classes/PHPExcel/IOFactory.php';
$dest = "uploads/";
$excel = "2012-12-STANDARD.xls";
$objPHPExcel = PHPExcel_IOFactory::load($dest.$excel);

Categories