I am creating an excel file with different sheets. The different sheets are created by iteration. But my iteration results in an extra sheet named worksheet. My code is:
$result = fetch results from database;
$count = COUNT($result);
foreach ( $result as $key=>$value){
$objPHPExcel->createSheet($key);
$objPHPExcel->getActiveSheet()
->setTitle($value['title']);
}
My database has got 3 results and it generates three worksheets along with a fourth one which is named as 'Worksheet'.
If I am using a checking condition with
if ($key > 0) {
execute above code
}
else {
$objPHPExcel->setActiveSheetIndex(0)->setTitle($value['title']);
}
it works fine. why is it so? Where is the mistake?
There is nothing wrong with your code. When you instantiate a new PHPExcel object using $objPHPExcel = new PHPExcel(), it is created with a single sheet called "worksheet"; delete that if you want to create only your own sheets
$objPHPExcel->removeSheetByIndex(0);
Mark Baker's accepted answer as always helped me but I want to expand and explain further on it.
I found that both $objPHPExcel = new PHPExcel() and $objPHPExcel->createSheet() create a single sheet called "worksheet". So use either one.
In the following sample which creates multiple sheets:
$objPHPExcel = new PHPExcel();
// First sheet
$objWorkSheet = $objPHPExcel->createSheet(); // NOT NEEDED
$objWorkSheet = $objPHPExcel->getActiveSheet();
// code for putting first sheet data
// Second sheet
$objWorkSheet = $objPHPExcel->createSheet();
// code for putting second sheet data
// Third, fourth sheets etc
createSheet() isn't needed for the first sheet where I've commented and it'll create that extra blank sheet. new PHPExcel() already made my first one me as he said.
So putting $objPHPExcel->removeSheetByIndex(0) at the end to remove it will work -- But just removing this unneeded line solves it the 'right' way and removes that redundancy. It seems like your code roughly does it like this.
Related
Be apprised that we are to trying export data to a particular worksheet of a workbook. For example, i'm trying to write "html" string to "Sheet - 2" in workbook_1.xls file. Based on the documentation and other related queries, i could not find as how we can achieve this. By default the data gets exported to the first sheet of the workbook.
This is the code i have tried until now.
$reader = new \PhpOffice\PhpSpreadsheet\Reader\Html();
$spreadsheet = $reader->load("filename.html");
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save('file'.xlsx');
How to solve this issue ?
You must select your spreadsheet. You can do it by name or number
// Get the second sheet in the workbook
// Note that sheets are indexed from 0
$spreadsheet->getSheet(1);
// Retrieve the worksheet called 'Worksheet 1'
$spreadsheet->getSheetByName('Worksheet 1');
More see documentation here.
I use the asimlqt/php-google-spreadsheet-client to read google spreadsheets and to write in google spreadsheets.
There are functions to update and delete the actual worksheet but not to empty the worksheet before i write data in it.
Knows somebody who use this library a way to empty the worksheet before writing in? If not you can not be sure that old data is still available
My personal solution is delete the worksheet and recreate
// service
$spreadsheetService = new Google\Spreadsheet\SpreadsheetService();
$spreadsheetFeed = $spreadsheetService->getSpreadsheetFeed();
// retrieve a list of worksheets from a spreadsheet
$spreadsheet = $spreadsheetFeed->getByTitle('Spreadsheet');
$worksheetFeed = $spreadsheet->getWorksheetFeed();
// get the worksheet you want to empty
$worksheet = $worksheetFeed->getByTitle('EmptySheet');
// delete the worksheet
$worksheet->delete();
// recreate the worksheet to be sure it's empty
$spreadsheet->addWorksheet('EmptySheet', rows, column);
Edit
Or use the batchUpdate with empty param userEnteredValue. Look at https://developers.google.com/sheets/api/samples/sheet#clear_a_sheet_of_all_values_while_preserving_formats
Currently using template excel sheet to add data, the requirement is add new sheet too, so need to add new sheet with same template.
My starts with new tamplate :
$filePath = public_path('Template.xls');
$objPHPExcel = PHPExcel_IOFactory::load($filePath);
Now, I have to create new sheet in same file with same tamplate without clone first sheet, because need to load fresh template without data.
You don't simply want to create a new sheet, you want to copy a sheet with all its existing styleing
So create a clone of the existing sheet, give it a new title (because worksheet titles must be unique), and attach that clone to the workbook.
$newSheet = clone $objPHPExcel->getActiveSheet();
$newSheet->setTitle('Worksheet 2');
$objPHPExcel->addSheet($newSheet);
You've modified the question since I posted the answer to your original question.
If you need to create a new worksheet from the template after you've already loaded the original template and populated it with data, then you'll need to reload the template as a new PHPExcel object, and inject the worksheet from that into your original workbook:
$filePath = public_path('Template.xls');
$objPHPExcel = PHPExcel_IOFactory::load($filePath);
// fill with data
$template = PHPExcel_IOFactory::load($filePath);
$newSheet = clone $template->getActiveSheet();
$objPHPExcel->addExternalSheet($newSheet);
the addExternalSheet() method ensures that all styles and structure (merged cells) are copied cleanly with the worksheet when it is added. Simply using the addSheet() method isn't guaranteed to copy that information correctly
I need to copy the content of one sheet in an Excel Workbook to a sheet in a new excel workbook. The issue is, I have no idea what the sheets contain or their formatting. However, it will only be the first sheet every time.
I've tried an approach but I run out of memory every time. So I thought I'd do it row by row for 100 000 rows. Anyway, I started with a row, and it gets the data, but no luck in writing it to a new sheet. How would I do that?
Here is what I have so far:
// Open the current worksheet
App::import('Vendor', 'PHPExcel');
if (!class_exists('PHPExcel')) {
throw new CakeException('Vendor class PHPExcel not found!');
$this->xls = PHPExcel_IOFactory::load($path);
// Read all content
$this->xls->getActiveSheet()->rangeToArray('A1:ZZZZ1');
// Close current worksheet
$this->xls->disconnectWorksheets();
// Delete worksheet
unlink($destination);
// Open new worksheet
$this->xls = new PHPExcel();
$newWorksheet = new PHPExcel_Worksheet($this->xls, 'Sheet 1');
$this->xls->addSheet($newWorksheet);
$this->xls->setActiveSheetIndexByName('Sheet 1');
// Write all the content
$this->xls->getActiveSheet()->fromArray($array,null,'A1');
// Save current worksheet
$objWriter = PHPExcel_IOFactory::createWriter($this->xls, 'Excel2007');
$objWriter->save($destination);
What am I doing wrong?
Then also, is there an easier way to do this? I don't want to write all this code and in the end it's all reinventing the wheel?
Thanks in advance
There's a built-in method that's specifically written to do this for you:
$objPHPExcel1 = PHPExcel_IOFactory::load($path);
$objPHPExcel2 = new PHPExcel();
// Copy active worksheet from $objPHPExcel1 to $objPHPExcel2
$worksheet = $objPHPExcel1->getActiveSheet();
$objPHPExcel2->addExternalSheet($worksheet)
and if you're running out of memory, building large arrays in memory to try and copy manually isn't going to help.
There are approaches designed to reduce memory such as cell caching, look to use those to reduce memory usage
I have a PHP parser using PHPExcel that reads in a Excel file and stores the contents into an Oracle database.
The problem is that the parser reads every line and does not set up any distinction between headers of rows and the data contained within those rows. When the info is read from the database it is read in a flat file listing and is not easy to navigate.
I am currently reading the data into an EXTJS Grid. I would like to be able to read the Excel, store it in the DB, then pull it out and view it in a new EXTJS GroupingGrid, where the group would be the 'header' for each worksheet in the Excel file.
Has anyone ever used PHPExcel or know how to use PHPExcel to read the Excel file and output the header (1,1) in each worksheet, so that I can store it in the database and pull it out and show it in the JSON so the groupingGrid will give me the ability to have a plus sign for each header so that I can click the plus sign and view all the contents under that header within the grid?
Hy, you can use this php-excell-reader http://code.google.com/p/php-excel-reader/ . I'm using it and works perfect. You can manipulate every cell of every row.
Count the cells
Count the rows
Make a loop to that count and manipulate data (you can add +1 if you want to skip
first row or first cell.
// Include the PHPExcel library
require_once './Classes/PHPExcel.php';
// Load the Excel File
$objReader = PHPExcel_IOFactory::createReader('Excel5');
$objPHPExcel = $objReader->load("myExcelFile.xls");
// Loop through every worksheet
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
// Read the value at Cell A1 in the current worksheet
$cellValue = $worksheet->getCell('A1')->getValue();
// Do whatever you want with $cellValue
// Store it in a database
// Whatever...
}
of course, you might want a bit of error handling in there as well, in case myExcelFile.xls doesn't exist, or you don't have read permissions, or isn't really an Excel file, but just wrap it in a try/catch block and handle as you wish.
You can also set up a read filter if you only want to load the first line of each worksheet rather than every single row and column:
// Include the PHPExcel library
require_once './Classes/PHPExcel.php';
/** Define a Read Filter class implementing PHPExcel_Reader_IReadFilter */
class firstRowFilter implements PHPExcel_Reader_IReadFilter
{
public function readCell($column, $row, $worksheetName = '') {
// Only read the heading row
return ($row == 1);
}
// Create an instance of our Read Filter
$firstRowFilter = new firstRowFilter();
// Instantiate the correct Reader
$objReader = PHPExcel_IOFactory::createReader('Excel5');
// Tell the Reader only to load cells that match our Read Filter
$objReader->setReadFilter($firstRowFilter)
// Load the Excel File
$objPHPExcel = $objReader->load("myExcelFile.xls");
// Loop through every worksheet
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
// Read the value at Cell A1 in the current worksheet
$cellValue = $worksheet->getCell('A1')->getValue();
// Do whatever you want with $cellValue
// Store it in a database
// Whatever...
}