Yii - how to read excel file sheets using yexcel plugin - php

I am using Yexcel - YII plugin that is a wrapper for PHPEXcel for a web application that need to read and parse different excel files.
http://www.yiiframework.com/extension/yexcel/
I am able to read and use the data in excel files that are single means they have only
one sheet but when it comes to reading other sheets in same excel file then i cannot read those because it gives me error.Using PHPExcel we can set active sheets and read
like this
$objPHPExcel->setActiveSheetIndex(0); // first sheet
but how can we do this using YII's yexcel plugin?
Because when i call this function with yexcel object it gives me error
Fatal error: Call to undefined method Yexcel::setActiveSheetIndex()
Issue: How to access all sheets in an Excel file.
Any help, guidance in right direction is much appreciated.

Use the import csv extension
yii import csv

You can either extend Yexcel class and write your own method based on Yexcel->readActiveSheet() or hardcode it (bad practice).
Below is my modified version:
public function readActiveSheet( $file, $activeSheet = 0 )
{
$objPHPExcel = PHPExcel_IOFactory::load($file);
$objPHPExcel->setActiveSheetIndex($activeSheet);
$sheetData = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
return $sheetData;
}
You can use it as following:
$sheet_attay = Yii::app()->yexcel->readActiveSheet($filename, 1);

Related

PhpSpreadsheet cannot read specific xls file

The following error
Fatal error: Uncaught PhpOffice\PhpSpreadsheet\Reader\Exception: Parameter pos=-12 is invalid
is given when trying to parse a specific xls file.
Code
$inputFileName = "excel.xls";
$reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xls');
$spreadsheet = $reader->load($inputFileName);
The file in question: https://filebin.net/sle19tm0kdgduyne/excel.xls?t=u0itbeue
I have tried using all available readers such as Xlsx, Csv etc and even using the old deprecated PHPExcel library. Nothing can parse this specific file, even though it opens fine with excel on windows.
My end goal is converting this xls file to an array, so i can paste the data into a database.
I think you don't need to use createReader().
Here the example of my worked code.
$reader = new \PhpOffice\PhpSpreadsheet\Reader\Xls();
$spreadsheet = $reader->load('path/to/file.xls');
Hope this can help you.

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

File downloaded via Podio Export API is not readable through code

Use-case:
Export data from different apps using batch EXPORT APIs to merge into a master excel file and use it for reporting purpose...
Implementation Details
I'm using Podio export API to get data from an application. Application name is Kall8-number-text (as an example).. here is the code snippet
Code Snippet
$batch_id = PodioItem::export(11804702,"xlsx",array("filters" => array( "kall8-number-text" => "510-592-5916") ));
PodioBatch::get( $batch_id );
$file = PodioFile::get($file_id);
// Download the file. This might take a while...
$file_content = $file->get_raw();
// Store the file on local disk
$path_to_file= "downloads/".$name;
file_put_contents($path_to_file, $file_content);
Problem Description:
I'm trying to read downloaded file using phpexcel library but getting error "You tried to set a sheet active by the out of bounds index: 0. The actual number of sheets is 0"
This error shows that file has NO sheet but it is not true. File has data/sheet and it shows upon opening that file.
One interesting fact, if I open the same excel file (manually by double click) and SAVE without making any change, then same code works fine. In my end to end process, I cannot add a manual step to open file every-time to proceed further...
For your information, I thought this is a PHPExcel bug and contacted Mark Backer (coordinator PHPOffice Suit) and he replied with following remarks which seems true.
"My guess would be non-standard namespacing in the file that's generated, which loading and saving in MS Excel fixes"
File Reading Code
$objReader = new PHPExcel_Reader_Excel2007();
$objReader->setReadDataOnly(true);
$objPHPExcel = $objReader->load('callsheet.xlsx');
$objPHPExcel->setActiveSheetIndex(0);
$dataArray = $objPHPExcel->getActiveSheet()->toArray(null, true,true,true);
var_dump($dataArray);
Error Trace
Fatal error: Uncaught exception 'PHPExcel_Exception' with message 'You tried to set a sheet active by the out of bounds index: 0. The actual number of sheets is 0.' in E:\xampp\htdocs\podioexcel\Classes\PHPExcel.php:688 Stack trace: #0 E:\xampp\htdocs\podioexcel\test.php(18): PHPExcel-
setActiveSheetIndex(0) #1 {main} thrown in E:\xampp\htdocs\podioexcel\Classes\PHPExcel.php on line 688
Can you help me to address this issue? This is holding up my project completely.
File Path: https://drive.google.com/file/d/0B79S561prrEBUDY1NEhXQ1JySWM/view
Original question at Stackoverflow: Error While loading excel sheet Using phpexcel
Ejaz

phpexcel - using it with excel template (chart goes missing) php

I have tried to use phpexcel with my own template file. phpexcel loads the file and writes data to some cells A2, A3, A4 for example.. and opens an output file with the new data.
my template file has chart built-in.. all i want to phpexcel to do is to populate values in cells and don't touch the chart. And, open the new file. (Please note that I don't want to make the chart in code.. I want the chart to pre-exist with in my template in same format as I created originally). Only the data should update.
But, when i try to do this.. the chart itself goes missing from the resulting file. After trying various ways.. still failed.
And, i found the following code from http://phpexcel.codeplex.com/discussions/397263
require_once 'Classes/PHPExcel.php';
/** PHPExcel_IOFactory */
include 'Classes/PHPExcel/IOFactory.php';
$target ='Results/';
$fileType = 'Excel2007';
$InputFileName = $target.'Result.xlsx';
$OutputFileName = $target . '_Result.xlsx';
//Read the file (including chart template)
$objReader = PHPExcel_IOFactory::createReader($fileType);
$objReader->setIncludeCharts(TRUE);
$objPHPExcel = $objReader->load($InputFileName);
//Change the file
$objPHPExcel->setActiveSheetIndex(0)
// Add data
->setCellValue('C3','10' )
->setCellValue('C4','20' )
->setCellValue('C5','30')
->setCellValue('C5','40' );
//Write the file (including chart)
PHPExcel_Settings::setZipClass(PHPExcel_Settings::PCLZIP);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, $fileType);
$objWriter->setIncludeCharts(TRUE);
$objWriter->save($OutputFileName);
The above code works in excel 2010 and now keeps my chart in tact... but still when I try to use filetype "Excel5" it doesn't work.
It throws the following error:
Fatal error: Call to undefined method PHPExcel_Reader_Excel5::setIncludeCharts()
in D:\IT\bfstools\PHPExcel\MyExamples\test1.php on line 16
Please provide a simple solution where I want my template file to work with .xls and .xlsx and all my original chart in the template file should stay intact. I do not want the chart removed it from the resulting file. Neither do I plan to create the chart using phpexcel code. (why write unnecessary code when excel can do all the work for you).
I want the easiest way out which is just to use everything with in my template and just populate cells with new data. And, my existing chart in the template comes live automatically. I don't want to write unnecessary code while I can safely rely on excel template and charting functions.
Please help.
There's a very good reason for this:
Charting is only implemented in core, and for the Excel2007 Readers and Writers at this point in time, so all of the other readers or writers will ignore charts, treat them as though they simply don't exist. The intention is to roll out charting to the other readers/writers over the coming year.
EDIT
I see from your comment that you don't understand how PHPExcel works at all, so I have a lot of explaining to do.
PHPExcel is not a library for "editing" workbook files: you're not using PHPExcel to change a file, you're changing a PHPExcel object that can be loaded from a file, and can subsequently be written to a file.
PHPExcel Core is an in-memory representation of the spreadsheet, with the different constituent objects such as worksheets, cells, images, styles, etc all represented as PHP Objects.
The PHPExcel Readers parse a spreadsheet file and load all the components from a file that they have been programmed to recognise, and create the appropriate PHPExcel core objects from those file components. If there is no equivalent PHPExcel Core object (such as Pivot Tables), then that file component can't be "loaded"; if the loader hasn't been programmed to recognise a file component, then it can't be loaded. In these cases, those elements from the file are simply ignored. Once the Reader has done it's job, a PHPExcel object exists, and the spreadsheet file is closed and forgotten.
When a PHPExcel Core object exists in memory, you have a set of methods allowing you to manipulate and change it, to add, modify or delete Core elements; but these work purely on the "in memory" collection of worksheet, cell, style objects that comprise the PHPExcel Core. The Core exists without knowledge of having been loaded from a file or having been created using a PHP "new PHPExcel()" statement; it makes no changes to files in any way.
When writing, the reverse is true. Each Writer takes the PHPExcel core objects, and writes them to a file in the appropriate format (Excel BIFF, OfficeOpenXML, HTML, etc). Like the Readers, each writer can only write those PHPExcel Core objects that it has been programmed to write. If it has not been programmed to write (for example, charts) then any charts defined in the PHPExcel Core will be ignored because that writer simply doesn't know how to write them yet. Likewise, features that exist in PHPExcel Core that are not supported by the file format that is being written to (such as cell styles for the CSV Writer) are ignored.
So to support a spreadsheet feature such as charts, it is necessary for the PHPExcel Core object collection to have been modified to provide an "in memory" representation of those elements, and for the different Readers to have been programmed to recognise those elements in the file they are loading and to convert them to the appropriate PHPExcel Core objects, and for the different Writers to have been programmed to convert the PHPExcel core representation to the appropriate file representation.
Each Reader and each Writer needs to be programmed individually. Charts is a relatively new feature, only added to the PHPExcel Core in the 1.7.7 release, and at this point only the Reader and Writer for the Excel2007 format have been programmed to recognise chart elements.
While it is the intention of the developers to extend this to cover the other formats as well, the necessary code isn't created automagically. Programming each individual Reader and Writer takes time and effort. While the Chart code for the Excel2007 Reader and Writer has now stabilised to the point where it is now no longer considered "experimental", and development focus is turning to writing the necessary code for chart handling in the Excel5 Reader and Writer, it is work that has not yet been completed.
If you can use Golang, try Excelize. Support save file without losing original charts of XLSX.
Try set setIncludeCharts
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
// Tell the reader to include charts when it loads a file
$objReader->setIncludeCharts(TRUE);
// Load the file
$objPHPExcel = $objReader->load($filePath);

How to modify existing excel file using PHP?

I have a excel i need to add some more sheets into the excel using PHP, i have used PEAR, there i tried only can write excel and read a file, not able to read and modify the file, guys can you help me in this?
Thanks in advance
Prabu
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();
?>

Categories