How to write only active sheet of xlsx file PHPSpreadsheet - php

i want to show the xlsx file as html, but it always return the first sheet of the file. What i want is to get the writer to show the one active sheet only if there are multiple sheets (name and order of sheet are random).
here is my code :
public function view_excel($path){
$file = realpath(FCPATH)."/uploads/PKB/".$path;
$reader = IOFactory::createReader('Xlsx');
$spreadsheet = $reader->load($file);
// $spreadsheet = $spreadsheet->getActiveSheet();
$writer = IOFactory::createWriter($spreadsheet, 'Html');
$message = $writer->save('php://output');
}
is there a way to do this ? Thanks

i managed to do this :
public function view_excel($path){
$file = realpath(FCPATH)."/uploads/PKB/".$path;
$reader = IOFactory::createReader('Xlsx');
$spreadsheet = $reader->load($file);
$active_sheet = $spreadsheet->getActiveSheet()->getTitle();
$reader->setLoadSheetsOnly($active_sheet); //only load active sheet
$worksheet = $reader->load($file);
$writer = IOFactory::createWriter($worksheet, 'Html');
$message = $writer->save('php://output');
}
had to load the file twice

Here you go!
public function view_excel($path){
$file = realpath(FCPATH)."/uploads/PKB/".$path;
$reader = IOFactory::createReader('Xlsx');
$spreadsheet = $reader->load($file);
$writer = IOFactory::createWriter($spreadsheet, 'Html');
-> $writer->setSheetIndex($spreadsheet->getActiveSheetIndex());
$message = $writer->save('php://output');
}

Related

How to remove all merged cells from an Excel file in php?

I have a Excel file like this:
I wrote a code that allows me to extract all the photos from the xlsx file and insert them in a folder.
There are several merged cells in the file and before processing I would like to remove all the merged cells from the Excel file. I tried with $objPHPExcel->setActiveSheetIndex("0")->unmergeCells(); but it doesn't work.
How can I solve my problem?
<?php
//uploaded xlsx file recovery
$xlsx="C:/wamp64/www/Extract_pictures_Excel/xlsx_files/".date('Y_m_d H-i-s')."_file.xlsx";
move_uploaded_file($_FILES["mon_fichier"]["tmp_name"],$xlsx);
require_once 'PHPExcel/Classes/PHPExcel/IOFactory.php';
$objPHPExcel = PHPExcel_IOFactory::load($xlsx);
//Unique name folder for the pictures
$dirname = uniqid();
mkdir("C:/wamp64/www/Extract_pictures_Excel/pictures_folders/$dirname/");
$sheet = $objPHPExcel->getActiveSheet();
//Unmerge all cells
foreach($sheet->getMergeCells() as $cells)
{
$sheet->unmergeCells($cells);
// var_dump($cells);
}
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
$objWriter->save('./unmerged_files/unmerged.xlsx');
//reading the xlsx file
foreach ($sheet->getDrawingCollection() as $drawing ) {
if ($drawing instanceof PHPExcel_Worksheet_MemoryDrawing) {
ob_start();
call_user_func(
$drawing->getRenderingFunction(),
$drawing->getImageResource()
);
$imageContents = ob_get_contents();
ob_end_clean();
switch ($drawing->getMimeType()) {
case PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_PNG :
$extension = 'png'; break;
case PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_GIF:
$extension = 'gif'; break;
case PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_JPEG :
$extension = 'jpg'; break;
}
} else {
$zipReader = fopen($drawing->getPath(),'r');
$imageContents = '';
while (!feof($zipReader)) {
$imageContents .= fread($zipReader,1024);
}
fclose($zipReader);
$extension = $drawing->getExtension();
$chemin = "C:/wamp64/www/Extract_pictures_Excel/pictures_folders/$dirname/";
}
//retrieving cell values for the images name
$row = (int) substr($drawing->getCoordinates(), 1);
//Condition to read merged cell
$stylecode = $sheet->getCell('H'.$row)->getValue();
$colorcode = $sheet->getCell('E'.$row)->getValue();
$finalname = $stylecode.'_'.$colorcode;
$myFileName = $chemin.$finalname.'.'.$extension;
file_put_contents($myFileName, $imageContents);
}
?>
I have changed the library to PhpOffice\PhpSpreadsheet because PHPExcel is outdated.
require_once './vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
$xlsx = './test/catalogmtnwr2021202009210323241.xlsx';
$spreadsheet = IOFactory::load($xlsx);
$sheet = $spreadsheet->getActiveSheet();
Now I am testing what is merged and unmerge it
echo 'before unmerge: ', count($sheet->getMergeCells()), PHP_EOL;
foreach($sheet->getMergeCells() as $cells)
$sheet->unmergeCells($cells);
echo 'after unmerge: ', count($sheet->getMergeCells()), PHP_EOL;
before unmerge: 678
after unmerge: 0
And at last write back into file
$writer = new Xlsx($spreadsheet);
$writer->save('./test/unmerged.xlsx');
This unmerged the cells as expected

PHPEXCel Read only one sheet to Array

I am using PHPExcel to only read values from excel sheets
if i use this code , it works fine without no problem:
function ReadUploadedFile($Uploadedfile,$fileExtension)
{
class MyReadFilter implements PHPExcel_Reader_IReadFilter
{
public function readCell($column, $row, $worksheetName = '')
{
// Read rows 1 to 7 and columns A to E only
if ($row>=1 && $row<=100) {
if (in_array($column,range('A','Z'))) {
return true;
}
}
return false;
}
}
}
$filterSubset = new MyReadFilter();
$inputFileType="";
$inputFileType = 'Excel5';
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objReader->setReadFilter($filterSubset);
$objReader->setReadDataOnly(true);
$objPHPExcel = $objReader->load('myExcelsheet.xls');
$sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
$sheetData now is an array and i can use it with no problem.
what if i have many worksheets ,and i need to specify only one , as per documentation from PHPEXCEL , they say to use setLoadSheetsOnly()
i try the code blow but it doesn't work.
$inputFileType = 'Excel2007';
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objReader->setReadFilter($filterSubset);
$objReader->setReadDataOnly(true);
$objReader->setLoadSheetsOnly("Summary"); //my worksheet name is Summary
$objPHPExcel = $objReader->load('myExcelsheet.xlsx');
so what should i write after the above line to convert this object to Array
i try this
$sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
but it gives this error
Call to a member function cellExists() on a non-object
and when i try this
$sheetData = $objPHPExcel->toArray(null,true,true,true);
Call to undefined method PHPExcel::toArray()
/** Here is my code work: */
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
define('EOL', (PHP_SAPI == 'cli') ? PHP_EOL : '<br/>');
/** PHPExcel_IOFactory */
require_once dirname(__FILE__) . '/../Classes/PHPExcel/IOFactory.php';
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$inputFileType = 'Excel2007';
$inputFileName = 'file.xlsx';
$sheetname = 'mysheey'; // I DON'T WANT TO USE SHEET NAME HERE
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objReader->setLoadSheetsOnly($sheetname);
$objPHPExcel = $objReader->load($inputFileName);
$sheetData = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
echo ' Highest Column ' . $getHighestColumn = $objPHPExcel->setActiveSheetIndex()->getHighestColumn(); // Get Highest Column
echo ' Get Highest Row ' . $getHighestRow = $objPHPExcel->setActiveSheetIndex()->getHighestRow(); // Get Highest Row
echo "<pre>";
print_r($sheetData);
echo "</pre>";
Work for me.
I'm using: rangeToArray();
"phpoffice/phpspreadsheet": "^1.3"
$reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
$spreadsheet = $reader->load('report.xlsx');
$worksheet = $spreadsheet->setActiveSheetIndex(0);
$highestRow = $worksheet->getHighestRow();
$highestCol = $worksheet->getHighestColumn();
print_r($worksheet->rangeToArray("A4:$highestCol$highestRow", null, true, false, false));
// If you want to format data e.g. 2450 to 2,450
// You could set rangeToArray parameter at 4 = true

Combine two or more xls files as worksheets PHPExcel

I've been looking everywhere on how to do this with two existing files, looks like all documentation is on creating new files. I'd like to take one of the files and add the second file to it as a new worksheet then save it to the server.
I've been trying with no avail like this:
$file="test.xls";
$file2="test2.xls";
$outputFile = "final.xls";
$phpExcel = new PHPExcel($file);
$phpExcel->getActiveSheet();
$phpExcel->setActiveSheetIndex(0);
$phpExcel->addSheet($file2);
header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=$outputFile");
header("Cache-Control: max-age=0");
$objWriter = PHPExcel_IOFactory::createWriter($phpExcel, "Excel5");
file_put_contents($outputFile, $objWriter);
Any help would be greatly appreciated. Very new to PHP.
Doesn't anybody ever read documentation these days? There's a whole document in the folder called /Documentation about reading files to PHPExcel objects (it's called PHPExcel User Documentation - Reading Spreadsheet Files), together with dozens of examples (the /Documentation/Examples/Reader folder is a good place to look), and none of them use new PHPExcel($file). Nor do any of the examples or any of the documents say to use file_put_contents() when saving.
$file1="test.xls";
$file2="test2.xls";
$outputFile = "final.xls";
// Files are loaded to PHPExcel using the IOFactory load() method
$objPHPExcel1 = PHPExcel_IOFactory::load($file1);
$objPHPExcel2 = PHPExcel_IOFactory::load($file2);
// Copy worksheets from $objPHPExcel2 to $objPHPExcel1
foreach($objPHPExcel2->getAllSheets() as $sheet) {
$objPHPExcel1->addExternalSheet($sheet)
}
// Save $objPHPExcel1 to browser as an .xls file
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel1, "Excel5");
header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=$outputFile");
header("Cache-Control: max-age=0");
$objWriter->save('php://output');
// update from office site
$filenames = array('doc1.xlsx', 'doc2.xlsx');
$bigExcel = new PHPExcel();
$bigExcel->removeSheetByIndex(0);
$reader = PHPExcel_IOFactory::createReader($input_file_type);
foreach ($filenames as $filename) {
$excel = $reader->load($filename);
foreach ($excel->getAllSheets() as $sheet) {
$bigExcel->addExternalSheet($sheet);
}
foreach ($excel->getNamedRanges() as $namedRange) {
$bigExcel->addNamedRange($namedRange);
}
}
$writer = PHPExcel_IOFactory::createWriter($bigExcel, 'Excel5');
$file_creation_date = date("Y-m-d");
// name of file, which needs to be attached during email sending
$saving_name = "Report_Name" . $file_creation_date . '.xls';
// save file at some random location
$writer->save($file_path_location . $saving_name);
// More Detail : with different object:
Merge multiple xls file into single one is explained here:
I'm going to describe a bit different:
http://rosevinod.wordpress.com/2014/03/15/combine-two-or-more-xls-files-as-worksheets-phpexcel/
// Combine all .csv files into one .xls file,
$cache_dir = "/home/user_name/public_html/";
$book1 = $cache_dir . "book1.csv";
$book2 = $cache_dir . "book2.csv";
$outputFile = $cache_dir . "combined.xls";
$inputFileType = 'CSV';
$inputFileNames = array($book1,$book2);
$objReader = new PHPExcel_Reader_CSV();
/** Extract the first named file from the array list **/
$inputFileName = array_shift($inputFileNames);
/** Load the initial file to the first worksheet in a PHPExcel Object **/
$objPHPExcel = $objReader->load($inputFileName);
/** Set the worksheet title (to the filename that we've loaded) **/
$objPHPExcel->getActiveSheet()
->setTitle(pathinfo($inputFileName,PATHINFO_BASENAME));
/** Loop through all the remaining files in the list **/
foreach($inputFileNames as $sheet => $inputFileName) {
/** Increment the worksheet index pointer for the Reader **/
$objReader->setSheetIndex($sheet+1);
/** Load the current file into a new worksheet in PHPExcel **/
$objReader->loadIntoExisting($inputFileName,$objPHPExcel);
/** Set the worksheet title (to the filename that we've loaded) **/
$objPHPExcel->getActiveSheet()->setTitle(pathinfo($inputFileName,PATHINFO_BASENAME));
}
$objWriter = new PHPExcel_Writer_Excel5($objPHPExcel);
$objWriter->save( $outputFile );
$objPHPExcel->disconnectWorksheets();
unset($objPHPExcel);
echo "DONE";

PHPExcel converting multiple sheet of xlsx to csv

im using this few lines to convert an xlsx, which contain 4sheets to convert to .csv . but it only convert the first sheet of the xlsx file. how can i make it to convert every sheets in the xlsx. heres the code,
error_reporting(E_ALL);
date_default_timezone_set($this->vendor_timezone);
/** PHPExcel_IOFactory */
require_once sfConfig::get('sf_root_dir').'/lib/PHPExcel/IOFactory.php';
$file=sfConfig::get("sf_upload_dir").DIRECTORY_SEPARATOR."temp".DIRECTORY_SEPARATOR."1344500254_MyExcel.xlsx";
// Check prerequisites
//print sfConfig::get("sf_upload_dir").DIRECTORY_SEPARATOR."temp".DIRECTORY_SEPARATOR; exit;
if (!file_exists($file)) {
exit($file."Please run 06largescale.php first.\n");
}
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$objPHPExcel = $objReader->load($file);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV');
$objWriter->save(str_replace('.xlsx', '.csv',$file));
return "success";
Please check the tutorial here which has step by step code to achieve this
<?php
require_once 'PHPExcel/PHPExcel/IOFactory.php';
$excel = PHPExcel_IOFactory::load("test123.xlsx");
$writer = PHPExcel_IOFactory::createWriter($excel, 'CSV');
$writer->setDelimiter(";");
$writer->setEnclosure("");
$writer->save("test123.csv");
?>
To convert all sheets you must iterate through all worksheets and set it as the active sheet and then write that to a file.
$inFile = 'fileWithMultipleWorksheet.xlsx';
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$objPHPExcel = $objReader->load($inFile);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV');
$index = 0;
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
$objPHPExcel->setActiveSheetIndex($index);
// write out each worksheet to it's name with CSV extension
$outFile = str_replace(array("-"," "), "_", $worksheet->getTitle()) .".csv";
$objWriter->setSheetIndex($index);
$objWriter->save($outFile);
$index++;
}
Write each sheet in turn to a different file, and then concatenate those files into one: PHPExcel does not provide an option to write multiple sheets to a single CSV file.

How to split the Excel file that contains multiple sheets?

I have the Excel file that contains a few sheets. How to split this file to get get each sheet as a separate file?
From PHP, you'llneed to have something like phpExcel to open the spreadsheet, and rewrite each tab as a new file.
Using the PHPExcel library:
include 'PHPExcel.php';
$fileType = 'Excel2007';
$inputFileName = 'testExcel.xlsx';
$objPHPExcelReader = PHPExcel_IOFactory::createReader($fileType);
$objPHPExcel = $objPHPExcelReader->load($inputFileName);
$sheetIndex = 0;
$sheetCount = $objPHPExcel->getSheetCount();
while ($sheetIndex < $sheetCount) {
++$sheetIndex;
$workSheet = $objPHPExcel->getSheet(0);
$newObjPHPExcel = new PHPExcel();
$newObjPHPExcel->removeSheetByIndex(0);
$newObjPHPExcel->addExternalSheet($workSheet);
$objPHPExcelWriter = PHPExcel_IOFactory::createWriter($newObjPHPExcel,$fileType);
$outputFileTemp = explode('.',$inputFileName);
$outputFileName = $outputFileTemp[0].$sheetIndex.'.'.$outputFileTemp[1];
$objPHPExcelWriter->save($outputFileName);
}

Categories