Get named ranges in PHPExcel - php

Using PHPExcel, I would like to loop through all the named ranges in a workbook and then create a new tab for each one.
I am currently doing this in excel with a macro, like so:
Dim sheetName As String
sheetName = ActiveSheet.Name
Dim nName As Name
For Each nName In Names
If InStr(1, nName.RefersTo, sheetName) > 0 Then
Application.Goto Reference:=nName.Name
Selection.Copy
Sheets.Add After:=Sheets(Sheets.Count)
ActiveSheet.Name = nName.Name
Selection.PasteSpecial Paste:=xlPasteValues
End If
Next nName
mystring = Sheets(1).Name
ActiveWorkbook.SaveCopyAs Filename:="P:\DP\CWBI\" & mystring & "_parsed.xls"
I can loop through active sheets in PHPExcel and dump them into an array for processing, like this:
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$sheets = $objReader->listWorksheetNames($file);
print_r ($sheets);
Does anyone know if it's possible to loop through all the named ranges?
Edit:
I'm trying the first suggestion below, but not getting any output. Here's the code:
$file="span_test.xlsx";
$objPHPExcel = PHPExcel_IOFactory::load($file);
foreach($objPHPExcel->getNamedRanges() as $name => $namedRange) {
echo $namedRange . "</br>";
}
Got it working now, my mistake in trying to echo an object. should be
print_r($name)

You have to actually load the workbook to access the named ranges
foreach($objPHPExcel->getNamedRanges() as $name => $namedRange) { ... }
which returns a PHPExcel_NamedRange object for each named range

Related

use "exceldatatables" to join two sheets of a different workbook

I have to create an Excel file with a data sheet that will vary according to a database and a sheet containing multiple PivotTables that have their own PivotCharts.
"data.xlsx" contains a sheet with all new data.
"graph.xlsx" contains a sheet with old data and a sheet with PivotTables.
My goal is to have "graph.xlsx" containing a sheet with all new data and the sheet with PivotTables.
I found a perfect lib to do this : https://github.com/svrnm/exceldatatables
But I block on the use of it, I would open "graph.xlsx" delete its sheet named "brut data", then to add a new sheet named "brut data" initialized with the new data contained in "data.xlsx".
To do it I saw this function from ExcelWorkbook.php a Class of this lib.
public function addWorksheet(ExcelWorksheet $worksheet, $id = null, $name = null)
But I don't understand how to use it.
(I'm the author of the mentioned library)
There are two steps you need to take, to achieve your goal, the first is reading the data.xlsx. The second is writing that data into your graph.xlsx. The library is solving step two:
require_once('../vendor/autoload.php');
$dataTable = new Svrnm\ExcelDataTables\ExcelDataTable();
$in = 'graph.xlsx';
$out = 'out.xlsx';
$data = /* ... step 1 ... */
$dataTable->showHeaders()->addRows($data)->attachToFile($in, $out);
For step 1 you could leverage PHPExcel. I haven't tested it, but something similar like this:
$r = PHPExcel_IOFactory::createReader('Excel2007');
$data = $r->load($filename)->getActiveSheet()->toArray(null, true, true);
There is another option: You could unpack both graph.xlsx and data.xlsx and merge the sheets.

How to read subscript/superscript/new line using PHPExcel library when importing excel file to PHP and storing in MySQL

I am having trouble saving the excel file in mysql database, It contains enter(new line) inside a cell and symbols & superscripts as well. But it stores as plain text only.
$objReader = new PHPExcel_Reader_Excel5();
$objPHPExcel = $objReader->load($inputFileName);
$sheetData = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
then i read some data and use
reset($sheetData);
to reset the pointer.
and again use foreach() loop, to add the data into an array and insert that array to mysql table. Does any of these steps remove pre-formatting (superscript/subscript/new line inside a cell and bold/italics)? and How can I put the data in the table exactly as in the excel?
Edit: I am using v1.8 of PHPExcel, v5.4 of PHP and MySQL v5.6
include APPPATH.'/spreadsheetreader/php-excel-reader/excel_reader2.php';
require(APPPATH.'/spreadsheetreader/SpreadsheetReader.php');
require(APPPATH.'/spreadsheetreader/SpreadsheetReader_CSV.php');
require(APPPATH.'/spreadsheetreader/SpreadsheetReader_ODS.php');
require(APPPATH.'/spreadsheetreader/SpreadsheetReader_XLS.php');
require(APPPATH.'/spreadsheetreader/SpreadsheetReader_XLSX.php');
class Dashboard extends REST_Controller
{
public function __construct()
{
parent:: __construct();
$this->load->library("PHPExcel");
}
public function dashboard_post()
{
$Reader = new SpreadsheetReader('./upload/'.$filename);
$totalSheet = count($Reader->sheets());
//print_r($totalSheet);exit;
// For Loop for all sheets
if($totalSheet>0)
{
for($i=0;$i<$totalSheet;$i++)
{
$Reader->ChangeSheet($i);
foreach ($Reader as $Row)
{
$data=array(
'your table column name'=>isset($Row[1]) ? $Row[1] : '',
'your table column name'=>isset($Row[2]) ? $Row[2] : '',
'your table column name'=>isset($Row[3]) ? $Row[3] : '',
'your table column name'=>isset($Row[4]) ? $Row[4] : '',);
}
The toArray() method is intended to provide a simple function to get the plain text from data cells in a spreadsheet; so all "formatting" of rich text (cells that contain different styles, colours, newlines and font information for different parts of the cell content) is removed to provide that plain text.
If you want to access that style information, then you need to get the data from the individual cells yourself using the cell's getValue() method; so you'll need to write your own loop to do that for all cells in the sheet; and you'll need to decide how you're going to store things like superscripts or bold/italic/underline in your database, and parse rich-text cell data accordingly

Read excel sheet containing merged cells using PHPExcel

I want to read an excel sheet completely and using AJAX send each row to another page for processing. So I have used the following code for converting the excel sheet data into JSON array(Reference PHPExcel example provided in Library):
<?php
error_reporting(E_ALL);
set_time_limit(0);
date_default_timezone_set('Asia/Kolkata');
set_include_path(get_include_path() . PATH_SEPARATOR . 'PHPExcel-1.8/Classes/');
require_once 'PHPExcel/IOFactory.php';
$inputFileType = PHPExcel_IOFactory::identify($fileLocation);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objReader->setLoadSheetsOnly("SHEETNAME");
$objPHPExcel = $objReader->load($fileLocation);
$data = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
?>
Here $filelocation is the location of the uploaded file which is to be read for sending the rows individually using AJAX to another page.
I am using $data in javascript as
DataToBeUploaded=<?php echo json_encode($data);?>;
But the excel sheet contains some merged cells so PHPExcel is not able to read the values in these merged cells. Hence values in these cells are read as NULL.
Is there a way where I can use the merged cells' upper left cell value for all of the subsequent cells? (Actually in my case cells are merged vertically only)
Eg.
I have (Assume rows are numbered from 1 and columns from A)
Here PHPExcel reads this as:
data[1][A]='abc'
$data[1][B]='123'
$data[2][A]=''
$data[2][B]='456'
$data[3][A]=''
$data[3][B]='789'
I want the snippet to result in these values:
data[1][A]='abc'
$data[1][B]='123'
$data[2][A]='abc'
$data[2][B]='456'
$data[3][A]='abc'
$data[3][B]='789'
Referring to https://github.com/PHPOffice/PHPExcel/issues/643
I have written the following snippet:
$referenceRow=array();
for ( $row = 2; $row <= $noOfBooks; $row++ ){
for ( $col = 0; $col < 7; $col++ ){
if (!$objPHPExcel->getActiveSheet()->getCellByColumnAndRow( $col, $row )->isInMergeRange() || $objPHPExcel->getActiveSheet()->getCellByColumnAndRow( $col, $row )->isMergeRangeValueCell()) {
// Cell is not merged cell
$data[$row][$col] = $objPHPExcel->getActiveSheet()->getCellByColumnAndRow( $col, $row )->getCalculatedValue();
$referenceRow[$col]=$data[$row][$col];
//This will store the value of cell in $referenceRow so that if the next row is merged then it will use this value for the attribute
} else {
// Cell is part of a merge-range
$data[$row][$col]=$referenceRow[$col];
//The value stored for this column in $referenceRow in one of the previous iterations is the value of the merged cell
}
}
}
This will give the result exactly as required

convert an EXCEL file to CSV file in PHP [duplicate]

This question already has answers here:
How to convert Excel XLS to CSV using PHP
(5 answers)
Closed 7 years ago.
I want to convert Excel files (.xls) into CSV file (.csv) with a script PHP ?
I tried many codes but it didn't work like this one !
No errors appear but it wont work Any idea or any other lines of codes that I can try ?
<?php
echo("it works");
require_once '../batchs/Classes/PHPExcel/IOFactory.php';
$inputFileType = 'Excel5';
$inputFileName = '../public/aixstream/stock.xls';
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcelReader = $objReader->load($inputFileName);
$loadedSheetNames = $objPHPExcelReader->getSheetNames();
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcelReader, 'CSV');
foreach($loadedSheetNames as $sheetIndex => $loadedSheetName) {
$objWriter->setSheetIndex($sheetIndex);
$objWriter->save($loadedSheetName.'.csv');
}
?>
Thank you
As already stated in this answer, you can use the PHP-ExcelReader function to read the xls file. After that, you may easily convert it into CSV (or any other other format) using the following code, also available here.
Reading the xls file
//You will obviously need to import the function
//by downloading the file from the link above.
$reader=new Spreadsheet_Excel_Reader(); //Instantiate the function
$reader->setUTFEncoder('iconv'); // Set Encoder
$reader->setOutputEncoding('UTF-8'); // Set Output Encoding Type
$reader->read($filename); // Read the xls file
Data Output
/***
* Information about sheets is stored in boundsheets variable.
* This code displays each sheet's name.
***/
foreach ($reader->boundsheets as $k=>$sheet) //Run loop for all sheets in the file
{
echo "\n$k: $sheet";
}
//Now just save the data in the array as csv
/***
* Data of the sheets is stored in sheets variable.
* For every sheet, a two dimensional array holding table is created.
* This code saves all data to CSV file.
***/
foreach($reader->sheets as $k=>$data) // Run loop for all items.
{
echo "\n\n ".$reader->boundsheets[$k]."\n\n"; //Print Title
foreach($data['cells'] as $row) // Loop for all items
{
foreach($row as $cell) // Loop for every cell
{
echo "$cell".","; //Add a comma after each value
}
}
}
//It works! :D

Symfony, PHPExcel not accepting date array from database?

I'm having problems outputting an excel with its date object. I'm using PHPExcel on Symfony. I performed an SQL that grabs data from the database in my Symfony controller. Then I did a for loop to iterate through each rows of data. However when I added in the value of a date, it gives me an error:
FatalErrorException: Error: Cannot use object of type DateTime as array in ...\Symfony\vendor\phpoffice\phpexcel\Classes\PHPExcel\Cell\DefaultValueBinder.php line 86
Here is my code:
$excel = new PHPExcel();
$excel->setActiveSheetIndex(0);
// ..etc
for($results as $result) {
// codes..
->setCellValue('H'.$i, $result['date'])
}
It's not allowing me to output the excel because of this. Should I be converting it to a string?
I found the solution through looping through the cell with the date values and setting it as date by number format:
$excel = new PHPExcel();
$excel->setActiveSheetIndex(0);
// ..etc
$i = 3;
for($results as $result) {
$excel->getActiveSheet()->getStyle('H'.$i)
->getNumberFormat()->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDD2);
$date = \PHPExcel_Shared_Date::PHPToExcel($result['date']);
// codes..
->setCellValue('H'.$i, $result['date'])
}

Categories