Copying excel column and inserting into new array - php

Problem:
What I am trying to achieve is to copy a selected range of cells from one excel spreadsheet and insert it into a newly generated one using laravel-excel and phpspreadsheet libraries. So far, the code that I've got, sort of does that but not idealy.
Excel::load($file, function($reader)
{
$activeSheet = $reader->getActiveSheet();
$this->data = $activeSheet->rangeToArray(
'A1:A27', // The worksheet range that we want to retrieve
NULL, // Value that should be returned for empty cells
true, // Should formulas be calculated (the equivalent of getCalculatedValue() for each cell)
true, // Should values be formatted (the equivalent of getFormattedValue() for each cell)
true // Should the array be indexed by cell row and cell column
);
});
// Create new file.
$newExport = Excel::create('Filename', function($excel) {
$excel->sheet('Sheetname', function($sheet) {
$sheet->fromArray($this->data, null, 'B1', true);
});
});
// Export newly created file.
$newExport->export('xlsx');
The problem is that it also inserts column name into a first cell (0 on screenshot, as I had indexing turned off, with indexing on, it would insert A) , as you can see on a screenshot bellow.
Actual result:
Expected result:
Stuff I have tried:
Tried to turn off indexing inside rangeToArray method.
Add column name into ignore list (2nd parameted in fromArray()), but that's not pragmatic, as I would end up adding every single column name into ignore list, moreover, it inserts blank value into first column and starts from B2 cell.
If anyone could give me some ideas how to resolve this case, that would be great.
Thanks!

The answer to the case is following...
Read the documentation for the library that you're actually using, rather than the one it's based on.
The reason why it was adding column headings, was due to laravel-excel library fromArray method default property values, which has heading generation enabled by default.
$sheet->fromArray($this->data, null, 'B1', true);
change to
$sheet->fromArray($this->data, null, 'B1', true, false);
Accepted parameters:
fromArray($source, $nullValue, $startCell, $strictNullComparison, $headingGeneration).

Related

Tables ignore given format

I'm trying to add some tables to a document, which after lot of work, it's showing right. Generated with PHPWord. The issue is that whatever I add in the table,row or cell style, it doesn't modify the table.
I've already tried: $table->addRow(15), $table->addRow(array('height'=>15)) and as is shown in the code below.
Also, there is no documentation on how to add a cell with two lines of text, because below 'Sign' I have to add 'Name'.
//TABLE1
$table = $section->addTable(array('width'=>100, 'borderSize'=> 1, 'borderColor'=>'000000'));
$table->addRow(15,array('height'=>15));
$table->addCell(array('width'=>150))->addText('COMPANY', $smallBoldFont);
$table->addRow();
$table->addCell()->addText('');
$table->addRow();
$table->addCell()->addText('');
//TABLE1
$section->addTextBreak(2);
//TABLE2
$table2 = $section->addTable(array('borderSize'=> 1, 'borderColor'=>'000000'));
$table2->addRow(100,array('height'=>80));
$table2->addCell(150,array('width'=>800))->addText('Recibed', $smallFont8);
$table2->addRow();
$table2->addCell()->addText('Time:', $smallFont8);
$table2->addCell()->addText('Sign:', $smallFont8);
//TABLE2
Is there a reason why PHPWord ignores my format style to tables? Is there any other way of doing it better?
Desired output:
Actual output:
In documentation is all. Just to read it deeply. Here is section how to create tables, including creation of tables with multicolumn cells
I don't know if PHPWord has some pre-defined units for case if you miss to use them. But it seems you need to set units for width. But you should test units and numbers as you need.
Order to create multicolumn cell is gridSpan(). So line for creation of the first row of the second table (probably) should be:
$table2->addCell(150,array('width'=>800))->gridSpan(2) ->addText('Recibed', $smallFont8);
PHPWord uses twip as default unit. And all cells have to match its width.
The smallest cell is taken for entire column.
For convertion from twips to other units may be used EndMemo (Topography Conversion Online).
250 pixels are 3750 twips.

How to find correct columns by data from 1st row phpexcel

I have excel file with some certain data i need.
"Category" is in first row of excel file.
Thing is that this data can be in different columns.
Is it possible to get column name based on data in first row ?
Example sheet:
For example, i need to get aircraft type and category, wich in this case are columns I & H.
At the moment i do it like this:
$allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
$arrayCount = count($allDataInSheet);
for($i=2;$i<=$arrayCount;$i++){
$aircraftType = trim($allDataInSheet[$i]["I"]);
$flightCategory = trim($allDataInSheet[$i]["H"]);
#insert all data in these columns to database
$query = "INSERT INTO {$databasetable} (aircraftType, flightCategory)
VALUES('$aircarftType', '$flightCategory')";
mysql_query($query) or trigger_error(mysql_error()." in ".$query);
}
But how can i do it, when i dont know column letter?
Maybe in next file aircraftType is in K and flightCategory is in L...
So is there a way to get column letter based on data in first row.
I think i could propably do it if i save all data to database, and then take it out with some where clauses, but maybe there is better way of doing this directly with PHPExcel ?
I am not really good explaining things, so sorry if this is confusing, please ask and i try to explain more.
Thanks in advance for help.
A simple call using the worksheet's rangeToArray() will give you an array of the headers
$headers = $objPHPExcel->getActiveSheet()
->rangeToArray(
'A1:'.$objPHPExcel->getActiveSheet()->getHighestColumn().'1',
null,
false,
false,
true
);
$headers = $headers[1];
The resultant array has the column letter as the key, and the cell content as the value; and you can then use it to map the appropriate columns to your data

PHPExcel taking format of empty cells

In an excel sheet where I previousely formatted the whole first colum as a date, I changed afterwards the format of the used cells to General (cells A1 to A11). So from cell A12, this first column still has the previous date format.
When I try to use the values of the first column (A1, A2, ..., A11) it identifies their format as a date, and gives a wrong result.
For example, this retruns a date format (d/mm/yyyy), which is not the case (see picture)
$sheet->getStyle('A3')->getNumberFormat()->getFormatCode();
Also the whole column has this format :
$sheet->getStyle('A')->getNumberFormat()->getFormatCode();
Is there a way to make sure the format of the cell itself is considered?
(when I indicated the format of this cells explicitely, the right format was used)
After some investigation, found that this problem occurs only for the .xlsx files (using reader PHPExcel_Reader_Excel2007) and not for the .xls files (reader PHPExcel_Reader_Excel5).
You can set the whole row/col format:
$sheet->getStyle('A')->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_TEXT);
Because you have changed only the format of A1 to A11, the rest are still with the old format. So setting format of the Whole Column/Row will fix this problem
After some more invetigation found a possible cause in reader Excel2007.php.
There is a problem with the condition When setting the style (line 933):
if ($c["s"] && !$this->_readDataOnly) {
$cell->setXfIndex(isset($styles[intval($c["s"])]) ? intval($c["s"]) : 0);
}
In case of General cell format, $c["s"] is not defined, and the _xfIndex of the cell is not set (not passing the if statement). This gives (I didn't found why) a problem with the stored _xfIndex of the cell.
When removing the $c["s"] condition, the right style is set.
if (/*$c["s"] &&*/ !$this->_readDataOnly) {
$cell->setXfIndex(isset($styles[intval($c["s"])]) ? intval($c["s"]) : 0);
}
Hoping there are no hidden consequences.

Zero in first of my cell data will remove in PHPExcel

I am trying to export my data to excel with PHPExcel,
I have a column which many of data on this column will start with 0 for example 0054672351 or 057524572 .
Now when I am trying to export to excel, my data will change to 54672351 or 57524572.
I am trying to change Data format of this column to text but I have this problem yet !
What should I do ?
For the second time of answering this same question here today:
Either:
// Set the value explicitly as a string
$objPHPExcel->getActiveSheet()
->setCellValueExplicit(
'A1',
'0054672351',
PHPExcel_Cell_DataType::TYPE_STRING
);
or
// Set the value as a number formatted with leading zeroes
$objPHPExcel->getActiveSheet()
->setCellValue('A3', 54672351);
$objPHPExcel->getActiveSheet()
->getStyle('A3')
->getNumberFormat()
->setFormatCode('0000000000');
Note that in the first case I'm calling the setCellValueExplicit() method, not the setCellValue() method.
If you're populating blocks of data in one step using the fromArray() method, then the latter approach is probably easier, especially as you can set the style for a whole block of cells in one step once you've populated all the data.
$objPHPExcel->getActiveSheet()
->getStyle('A3:A123')
->getNumberFormat()
->setFormatCode('0000000000');

Set data type in excel cells in PHP Excel class

Using PHP Excel class , how can I set percentage data type in Excel cells.
I tried with following code:
$objPHPExcel->getActiveSheet()->getStyle('I2')
->getNumberFormat()->applyFromArray(
array(
'code' => PHPExcel_Style_NumberFormat::FORMAT_PERCENTAGE_00
)
);
But in this case if I add value to 'I2' as '2.35', it displayed as '235.00%' in generated excel file.
Is there anyway to show it correctly?
This is MS Excel behaviour:
Open MS Excel, set a cell value to 2.35, then set the cell number format to percentage (with or without decimals) and you'll see 235.00% as the formatted value.
PHPExcel simply reflects this.
If you want to display 2.35% in Excel, then you need the cell value as 0.0235 and then set the number format mask to percentage. Do the same in PHPExcel, and you'll get the result you want
Note that this does not change the cell value in any way, simply the way that it is displayed.
Alternatively, set the number format mask to:
#,##0.00"%"

Categories