PHPExcel saving xlsx to xls, some cells are blank - php

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

Related

Change excel file extension from xls to xlsx while uploading with php

Is it possible and if is how can i change excel file extension while uploading or before saving file on server? I am using php and mysql.
Thankyou
You can do something like this.
move_uploaded_file($_FILES['file']['tmp_name'], upload_PATH.'/'.$_FILES['file']['name'].'x');
But that will only change the file name with the xlsx extension. It will not actually convert the file to xlsx format.
As previously mentioned in a different reply, changing the extension won't actually change the format, and it's not a good idea to serve a .xls file as .xlsx, since this will only confuse anyone trying to read it.
What you could do (disregarding potential problems with converting and verification of the file) is read the uploaded file into a library like PHPExcel (http://phpexcel.codeplex.com) and then use the builtin functions to export it as an .xlsx file. Sample below:
// Create a reader to read .xls format
$reader = PHPExcel_IOFactory::createReader('Excel5');
// Read the .xls file from upload storage
$workbook = $reader->load($_FILES['file']['tmp_name']);
// Create a writer to output in .xlsx format
$writer = PHPExcel_IOFactory::createWriter($workbook, 'Excel2007');
// Save file to destination .xlsx path
$writer->save($destination_path);
Keep in mind that although this might work perfectly well, the conversion might mess with the contents of the file. This might not be desirable, as the conversion can cause data loss, formatting changes and all sorts of weirdness.

PHPExcel creating file in binary format instead of xml

I am using PHPExcel to generate an Excel file. The problem is that, instead of generating the file in XML format, it is being generated in binary format.
$phpExcel = new PHPExcel();
$phpExcel->getProperties()->setTitle($worksheet_title);
$phpExcel->setActiveSheetIndex(0);
$worksheet = $phpExcel->getActiveSheet();
$worksheet->setCellValue('A1', 'Field');
// ...
$phpExcelWriter = PHPExcel_IOFactory::createWriter($phpExcel, 'Excel2007');
$phpExcelWriter->save('tmp/xxx');
Since I am using the Excel2007 writer, it should be creating the output file in readable xml format, but it's being created in binary format, instead.
An OfficeOpenXML file is not directly human-readable as one gigantasaurus of an xml file. It is a zipped archive containing a collection of XML files.
Unzip the .xlsx file, then you will find a series of folders containing xml files.
That is what MS Excel generates when you save a file as xlsx, and it is what PHPExcel generates as well
You can look at this link for full details of the OfficeOpenXML standard

I wanted to add data in pre formated Excel sheet using php

I wanted to append data in the pre formated excel sheet that is basically header footer in the excel sheet I wanted to append the contents. And will create many files dynamically.
A simple workaround is:
create a html table with the formatting you need
add values in php to the table (or generate table with php)
save file as .xls (filled with content from html table)
open file (will show formatted table in Excel)
Reason:
handling XLS files is very complex and many libraries have big limits (only available on windows servers....)
html table saved as .xls can be opened in Excel.
Thanks I have found the way PHPExcel is a good library.
In order to get PHPExcel http://www.codeplex.com/PHPExcel working with CodeIgniter, there are a few steps you must take to ensure compatibility with CodeIgniter's naming standards.
1: Class names must match the file names. PHPExcel has a few files(such as PHPExcel/IOFactory.php) that have names like PHPExcel_IOFactory. Change these names by removing the "PHPExcel_" part. These constructors in these files must be public in order for CI to access them.
$this->load->library('phpexcel');
$this->load->library('PHPExcel/iofactory');
$objPHPExcel = new PHPExcel();
$objPHPExcel->getProperties()->setTitle("title")
->setDescription("description");
// Assign cell values
$objPHPExcel->setActiveSheetIndex(0);
$objPHPExcel->getActiveSheet()->setCellValue('A1', 'cell value here');
// Save it as an excel 2003 file
$objWriter = IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save("nameoffile.xls");

Invalid file format when attempting to read Excel 2007 files in PHP

I am trying to read data from Excel 2003 but I want the system also to load Excel 2007 files. However Excel 2007 file is triggering the file format exception. The code that checks the format is here
if ($this->header ['ident'] != "\xD0\xCF\x11\xE0\xA1\xB1\x1A\xE1")
throw new compoundDocumentException ('Invalid file format');
In this line I would like to add the header indent for Excel 2007 which I didn't find wherever I tried.
How do I achieve this please?
Excel 2007 files (.XLSX files) use a completely different XML-based format from previous versions of Excel. Simply checking for a new header will not help you at all here -- you will need an entirely different file reader for these newer files.

How to create xlsx file without using any excel library PHP

This is right now I am using.
$mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
header('Content-Description: File Transfer');
header('Content-Type: ' . $mimeType);
header('Content-Disposition: attachment; filename='.basename($type.'.xlsx'));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
print "$header\n$data";
exit;
$header variable contains the header row of excel to be generated and looks like this
$header= "Business_Name\tBusiness_Type\tType";
separated by \t
and $data contains rows to be generated under header columns. They are also separated by \t and a row is terminated by \n.
With the current setup file is downloaded but it is not opening with ms excel and showing this message.
Excel cannot open the file "file name"
because the file format or file
extension is not valid. Verify that
the file format has not been corrupted
and that the file extension matches
the format of the file.
What header should be sent to server? or how do I generate that file?
I achieve this in a fast, sort of cheapskate way - because it's long and winded I'll just explain it in concept rather than code.
XLSX adheres to ISO 29500 which is publicly available if you want to manipulate a document thoroughly in php. Otherwise, realise that xlsx files are zipped archives of a bunch of xml files.
Make a template that you want, say it has alternating rows with styles of different types, making that in excel or an open xml editor of some description. Make sure you put some data in there, and make sure some fields are equal (just for learning purposes).
Then save your file as xlsx, rename it .zip, or open it in an archive extractor and observe the contents.
Firstly, note the [Content_Types].xml file, this describes the location of the major files in the archive and the standards to which it itself adheres and the content types of those files.
Everything outside the xl/ folder is just meta data really. But observe docProps/core.xml contains author, modification and timestamp information - which you can replace in php when you recreate this file. Also everything that is pointed to say, docProps/core.xml can be renamed to your tastes, [Content_Types].xml can't.
Okay so now you understand this, you'll begin observing ids thrown around the place. They love to use this in the file format, everything refers to everything else by its index in a particular xml property list or similar. They also usually describe the quantity of items in such lists.
In xl/ you'll see themes.xml, styles.xml, workbook.xml, sharedStrings.xml, _rels/, worksheets/.
Styles is going to be inflated with a whole lot of unnecessary styles that excel builds by default if you used it. But you should be able to see how these styles work such that you can customise your own.
Themes to me is rather pointless so I delete it and its referenced ids throughout.
Next up you'll see workbook, that's the file containing information regarding the sheets which are inside of the spreadsheet document since you can have more than 1 obviously. It also contains some sheet metadata such as its size etc.
Now comes the first big hua you'll encounter. sharedStrings.xml is a weird file which stores all the information that will be inserted into cells in a static spreadsheet. They are indexed, but the engine reading the document figures out what their indexes are. Anything which repeats can be referred back to its old index in the sheet itself (inside worksheets folder) as to save on file size in large documents with repeated values.
Not the attributes count and uniquecount in the sst element and what they obviously mean.
This is the stage in php where you populate an array of data containing what you want in your sheet, and dump it into an xml formatted list such as this file appears. Also note these files don't need to be jammed up without newlines or linefeed characters as with or without is still valid xml and they will work in readers regardless.
Check out the _rels folder, it's fairly obvious again.
Lastly is the sheet itself. The numbers in fields here refer to the indexed locations of strings in sharedStrings.xml. The attribute s is the style, t is the type of data in the field. R is the cell location though why it needs that is beyond me when it could really be figured out rather easily.
Producing this file in php shouldn't be too difficult either. Just use your indexes from your data array you used to make your sharedStrings.xml file.
Oh also sheet has column width information in it which you can figure out based on the font you used and automatically size them in php too if need be.
Lastly is the packaging of it all in php.
My code is in a class which receives data and specific saved files I created with excel to keep it simple.
$this->folder_structure_simple = Array(
"_rels/.rels" => "_rels__rels",
"docProps/app.xml" => "docProps_app_xml",
"docProps/core.xml" => "docProps_core_xml",
"xl/_rels/workbook.xml.rels",
"xl/theme/theme1.xml",
"xl/worksheets/sheet1.xml",
"xl/sharedStrings.xml",
"xl/styles.xml",
"xl/workbook.xml",
"[Content_Types].xml" => "Content_Types_xml"
);
$zip = new ZipArchive;
$res = $zip->open($this->file_name, ZipArchive::CREATE);
if($res === TRUE){
foreach($this->folder_structure_simple as $file => $function){
$zip->addFromString($file, $this->$funtion);
}
$zip->close();
echo 'ok';
}else{
return FALSE;
}
And functions produce the required data. Very fast, not very flexible.
What you have is actually a CSV file. Depending on your OS, your browser and your Excel version, then the browser will differently let you or not let your open the extensions CSV, XLS XLSX with the Excel software.
If you do want to have your data opened with Excel, then you can merge the data with an Excel template using OpenTBS. Use version 1.6.0 (or greater) which is currently in Release Candidate because it brings major facilities for Excel files.
In your title there is "no excel library PHP". I don't know why you have this specification but OpenTBS is not exactly an Excel library. It's a PHP tool for merging OpenOffice and Ms Office documents using templates.
What you have a CSV, not an XLSX file. XLSX is a ZIP-wrapped blob of XML. Change your MIME type to text/csv.

Categories