PHPSpreadsheet - How do create a extra tab? - php

I create in my php code a excel file with one tab and give it a name.
The code what i use is this.:
// CREATE PHPSPREADSHEET OBJECT
require "../vendor/autoload.php";
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Worksheet\Drawing;
// CREATE A NEW SPREADSHEET + POPULATE DATA
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle('Batch');
But how do i create a second tab with another name?
[solved]
// CREATE A NEW SPREADSHEET + POPULATE DATA
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle('Batch');
// Add some data
$spreadsheet->createSheet();
// Add some data
$spreadsheet->setActiveSheetIndex(1) ->setCellValue('A1', 'world!');
// Rename worksheet
$spreadsheet->getActiveSheet()->setTitle('URL Removed');
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$spreadsheet->setActiveSheetIndex(0);

You can add an extra tab like this:
$spreadsheet->createSheet();
// Zero based, so set the second tab as active sheet
$spreadsheet->setActiveSheetIndex(1);
$spreadsheet->getActiveSheet()->setTitle('Second tab');
If you like, you can read more here.

You can also try this way
//at the beginning of the code
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
$myWorkSheet = new \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet($spreadsheet, 'Extra Tab');
$spreadsheet->addSheet($myWorkSheet, 0);
$sheetIndex = $spreadsheet->getIndex(
$spreadsheet->getSheetByName('Extra Tab')
);
$spreadsheet->setActiveSheetIndex($sheetIndex);
For more information here

Related

How to add new row on Excel using PHPSpreadsheet

Hi I'm new to this library called PHPSpreadsheet.
I tried reading it's docs but I can't understand it.
I want to insert a new row on an existing Excel File and
here is what I have so far:
<?php
require '../vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
$inputFileName = 'Excel/hello.xlsx';
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($inputFileName);
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', 'Updated');
$writer = new Xlsx($spreadsheet);
$writer->save('../controller/excel/hello.xlsx');
?>
This inserts new data on the 'hello.xsls' file replacing the cell's previous data. How can I make it write data into a new row?
To create a new row, you need to call insertNewRowBefore() with the row number you want to insert before...
$sheet = $spreadsheet->getActiveSheet();
$sheet->insertNewRowBefore(1);
$sheet->setCellValue('A1', 'Updated');
You can also call it with a number of rows to insert, the default is 1.
If you want to append a row, you can call getHighestRow() to find the last row and add 1 to it for the new row. Also change the hard coding of the column in the setCellValue() call to use this row as well...
$sheet = $spreadsheet->getActiveSheet();
$row = $sheet->getHighestRow()+1;
$sheet->insertNewRowBefore($row);
$sheet->setCellValue('A'.$row, 'Updated');
Hello I think this issue came because of memory exhausted so increase your memory limit by php.ini file
like memory_limit = 256M
After increase memory limit , restart your apache
The accepted answer throws exception:
"Column references should not be numeric."
For me works:
...
$row = 'A' . ($sheet->getHighestRow() +1);
$sheet->insertNewColumnBefore($row);
$sheet->setCellValue($row, 'Hello World again!');
...

PHPSpreadsheet, Drawing - move and size with cells

I try to set the setting "Move and size with cells" for my images in PHPSpreadsheet, but cant find any information anywhere. Now my question is, if that feature is implemented yet, and if it is, how its called.
Maybe is too late for "help YOU" but this will be useful for another people
I had the same problem and found 2 "things"
Nothing
Google is a bunch of millons links/sublinks to 50 top-web. Google is the old AOL of 1998
But, I didn't give up and I could "fix" it. Actually, in the folder of PHPSpreadsheet you will see the next next path folder;
/PhpOffice/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx
There're a file called: Drawing.php, in this file you will find a function called: writeDrawing
there you will find the following code;
[Line: 152]
$objWriter->startElement('xdr:oneCellAnchor');
It must be replace with:
$objWriter->startElement('xdr:twoCellAnchor');
After, 2 o 3 lines, under those code you will find this code;
[Line:166 to 169]
$objWriter->startElement('xdr:ext');
$objWriter->writeAttribute('cx', \PhpOffice\PhpSpreadsheet\Shared\Drawing::pixelsToEMU($pDrawing->getWidth()));
$objWriter->writeAttribute('cy', \PhpOffice\PhpSpreadsheet\Shared\Drawing::pixelsToEMU($pDrawing->getHeight()));
$objWriter->endElement();
Add comment marks like "//" or "/* code */" and comment it for avoid these code lines. And now, add the following code;
$objWriter->startElement('xdr:to');
$objWriter->writeElement('xdr:col', $aCoordinates[0] - 1);
$objWriter->writeElement('xdr:colOff', \PhpOffice\PhpSpreadsheet\Shared\Drawing::pixelsToEMU($pDrawing->getWidth()));
$objWriter->writeElement('xdr:row', $aCoordinates[1]);
$objWriter->writeElement('xdr:rowOff', "0");
$objWriter->endElement();
In the following code, should be fix
[Line:178 to 182]
$objWriter->startElement('xdr:cNvPr');
$objWriter->writeAttribute('id', $pRelationId);
$objWriter->writeAttribute('name', $pDrawing->getName());
$objWriter->writeAttribute('descr', $pDrawing->getDescription());
$objWriter->endElement();
the fixed code (don't add "$objWriter->endElement()");
$objWriter->startElement('xdr:cNvPr');
$objWriter->writeAttribute('name', $pDrawing->getName() . $pRelationId);
$objWriter->writeAttribute('descr', $pDrawing->getDescription());
$objWriter->writeAttribute('id', $pRelationId+1);
At Now, in the [Line: 183] INSERT this code;
$objWriter->startElement('a:extLst');
$objWriter->startElement('a:ext');
$objWriter->writeAttribute('uri', "{FF2B5EF4-FFF2-40B4-BE49-F238E27FC236}");
$objWriter->endElement(); // this close a:ext
$objWriter->endElement(); // this close a:extLst
$objWriter->endElement(); // thise xdr:cNvPr [this will replace the $objWriter->endElement(); of Line 182. It was lost in the previous step
Now, a code like this;
require "../../PhpOffice/vendor/autoload.php";
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
...
$imgfile = base64_decode($img_from_query_sql);
$fname = "../tmp/".rand(). ".xlsx";
file_put_contents($fname, $imgfile);
$drawing = new PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
$Cell = $Letter[$j] . $row;
$drawing->setPath($fname);
$drawing->setCoordinates($Cell );
$drawing->setResizeProportional(false);
$drawing->setWidth(300);
$drawing->setHeight(300);
$drawing->setWorksheet($sheet);
$sheet->setTitle("TitleOfSheet");
$writer = new Xlsx($spreadsheet);
$writer->save("php://output");
...
Execute and download your excel with images. Check your images: right click->"Size and properties..."
Will appear a right-panel of "Image format". In sub-menu "properties" should be a 3 "radio option" (circle with black point)
Move and size with cells
Move but don't size with cells
Don't move or size with cells
Phpspreadsheet orignally, makes pictures with option 2-> Move but don't size with cells but, we changed the code of Drawing.php and now all images are created with option 1->Move and size with cells
At now, if we have a excel file with a list of "things" and 1 image per row, we can apply filters and if some rows doesn't have any image the following image-row will not overlapping over the visible row (matching results).
Each picture filtered will be hidden with is parent row, and each picture matching with filter will be 'stick' to his parent row as always should have been
UPDATE: 28-07-22 - SpreadSheet 1.23
In vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Drawing.php still exist a function called writeDrawing in line 184;
This functions has changed a bit since the last version I used. Now, writeDrawing have many improves and doesn't require edit any codeline;
Currenly, "BaseDrawing" is a data type that have a new method called;
setCoordinates2 (two) instead of setCoordinates (withtout "2" at end)
You can use setCoordinates2 in your main_custom_file_excel_creator.php like;
$Cell = "A2";
$drawing->setCoordinates2($Cell); //instead of setCoordinates
The updated function (writeDrawing) from line 184 to 340, will use $drawing. This $drawing variable is type BaseDrawing so, in line 187 it will check if is set or not and will store a boolean in $isTwoCellAnchor
It will help us for some setting like #Wind Cloud was looking. Can be solved doing a simple;
$drawing->setEditAs("absolute");
The new version 1.23 (2022-jul-28) have better class Drawing;
Now you can do it without any edit. You only need set the correct methods;
for Move but don't size with cells
require "../../PhpOffice/vendor/autoload.php";
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
...
$imgfile = base64_decode($img_from_query_sql);
$fname = "../tmp/somefile123.xlsx";
file_put_contents($fname, $imgfile);
$drawing = new PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
$Cell = "A2";
$drawing->setPath($fname);
$drawing->setCoordinates2($Cell ); //USE THE NEW METHOD SETTER
$drawing->setResizeProportional(false);
$drawing->setWidth(300);
$drawing->setHeight(300);
$drawing->setWorksheet($sheet);
$sheet->setTitle("TitleOfSheet");
$writer = new Xlsx($spreadsheet);
$writer->save("php://output");
A user called Wind Cloud asked;
I want to set "Don't move or size with cells" instead. Do you know
how? – Wind Cloud
In the new version ^1.23 will be very easy;
require "../../PhpOffice/vendor/autoload.php";
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
...
$imgfile = base64_decode($img_from_query_sql);
$fname = "../tmp/somefile123.xlsx";
file_put_contents($fname, $imgfile);
$drawing = new PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
$Cell = "A2";
$drawing->setPath($fname);
$drawing->setCoordinates**2**($Cell);
$drawing->setEditAs("absolute"); //HERE IS YOUR KEY
$drawing->setResizeProportional(false);
$drawing->setWidth(300);
$drawing->setHeight(300);
$drawing->setWorksheet($sheet);
$sheet->setTitle("TitleOfSheet");
$writer = new Xlsx($spreadsheet);
$writer->save("php://output");

How to add multiple worksheet in PHPExcel

How to add multiple worksheets using phpexcel class.
$this->excel = new PHPExcel();
Take a look at the PHPExcel documentation
// Create a new worksheet called "My Data"
$myWorkSheet = new PHPExcel_Worksheet($objPHPExcel, 'My Data');
// Attach the "My Data" worksheet as the first worksheet in the PHPExcel object
$objPHPExcel->addSheet($myWorkSheet, 0);

How to load excel template and write to it in PHPExcel?

How do I load an Excel Template with PHPExcel and write to its cells and also insert images to cells dynamically?
You can read your excel template like this with PHPExcel:
$objPHPExcel = PHPExcel_IOFactory::load("./forms/english/cash.xlsx");
and you can write to cells like this:
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A2', "No")
->setCellValue('B2', "Name")
->setCellValue('C2', "Email")
->setCellValue('D2', "Phone")
->setCellValue('E2', "Address");
see the example, 30template.php in github site
https://github.com/PHPOffice/PHPExcel/blob/develop/Examples/30template.php
load template :
$objReader = PHPExcel_IOFactory::createReader('Excel5');
$objPHPExcel = $objReader->load("templates/30template.xls");
see in the example write via
$objPHPExcel->getActiveSheet()->setCellValue()
to add image use PHPExcel_Worksheet_Drawing :
// Add an image to the worksheet
$objDrawing = new PHPExcel_Worksheet_Drawing();
$objDrawing->setName('My Image');
$objDrawing->setDescription('The Image that I am inserting');
$objDrawing->setPath('./images/myImage.png');
$objDrawing->setCoordinates('B2');
$objDrawing->setWorksheet($objPHPExcel->getActiveSheet());
Now you don't need load templates. Try to use the PHP Excel templator:
https://github.com/alhimik1986/php-excel-templator

PHPExcel Mulitple excel file in one HTML page

I have 2 xls, i want to plot this information into one HTML Page.
Note: For assumption i mentioned as xls. actual xls positions are already in the database table. i will just render these position and plot into HTML Page.
include_once("Classes/PHPExcel/IOFactory.php");
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
//first excel file
$objPHPExcel->getActiveSheet()
->setCellValue('c5','10');
$objPHPExcel->getActiveSheet()
->setCellValue('c6','20');
$objPHPExcel->getActiveSheet()
->setCellValue('c7','30');
$objPHPExcel->getActiveSheet()
->setCellValue('c8','40');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'HTML');
//second excel file
$objPHPExcel->getActiveSheet()
->setCellValue('c5','50');
$objPHPExcel->getActiveSheet()
->setCellValue('c6','60');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'HTML');
$objWriter->save('combinedexcelpage.html');
I'm not going to go through a long explanation of why this doesn't work, because it would take too long to explain; but there are a couple of solutions that you could take to achieve what you want:
Option #1
An Excel workbook comprises one or more worksheets, so you could create each "file" as a separate worksheet, rather than a separate file.
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
// First excel worksheet, (created when you instantiate a new PHPExcel object)
$objPHPExcel->getActiveSheet()
->setCellValue('c5','10');
$objPHPExcel->getActiveSheet()
->setCellValue('c6','20');
$objPHPExcel->getActiveSheet()
->setCellValue('c7','30');
$objPHPExcel->getActiveSheet()
->setCellValue('c8','40');
// Second excel worksheet
// Add new sheet, which should also set it as the new "active" sheet
$objPHPExcel->createSheet()
$objPHPExcel->getActiveSheet()
->setCellValue('c5','50');
$objPHPExcel->getActiveSheet()
->setCellValue('c6','60');
By default, the HTML Writer will only write a single worksheet (the first), but you can set it to write all sheets:
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'HTML');
$objWriter->writeAllSheets();
$objWriter->save('combinedexcelpage.html');
Option #2
The HTML Writer save() method will always generate a file stream (whether a filesystem file or php://output), but rather than using save(), you can call individual methods in the class to generate a string containing the formatted worksheet data, and build your own output from those "blocks".
$data = '';
// First excel file
$objPHPExcel1 = new PHPExcel();
$objPHPExcel1->getActiveSheet()
->setCellValue('c5','10');
$objPHPExcel1->getActiveSheet()
->setCellValue('c6','20');
$objPHPExcel1->getActiveSheet()
->setCellValue('c7','30');
$objPHPExcel1->getActiveSheet()
->setCellValue('c8','40');
$objWriter1 = PHPExcel_IOFactory::createWriter($objPHPExcel, 'HTML');
$objWriter1->generateStyles(false);
$data .= $objWriter1->generateHTMLHeader();
$data .= $objWriter1->generateSheetData();
// Second excel file
$objPHPExcel2 = new PHPExcel();
$objPHPExcel2->getActiveSheet()
->setCellValue('c5','50');
$objPHPExcel2->getActiveSheet()
->setCellValue('c6','60');
$objWriter2 = PHPExcel_IOFactory::createWriter($objPHPExcel2, 'HTML');
$objWriter2->generateStyles(false);
$data .= $objWriter2->generateSheetData();
$data .= $objWriter2->generateHTMLFooter();
file_put_contents('combinedexcelpage.html', $data);
Both of these options are described in section 6.8 of the developer documentation

Categories