I am trying to delete some worksheet from an Excel file (2007), i challenged to write on cells or get values from cell but i dont challenge to delete worksheet
I tried this code
$objPHPExcel = PHPExcel_IOFactory::load(PATH_FICHIER_TRAITES."CONCAT/Concat_".$file);
$nombreFeuille = $objPHPExcel->getSheetCount();
if($nombreFeuille>1){
for($i=1; $i<=$nombreFeuille; $i++){
$objPHPExcel->removeSheetByIndex($i);
}
}
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, "Excel2007");
$objWriter->save(PATH_FICHIER_TRAITES."CONCAT/Concat_".$file);
but my file remain the same after the execution
I would be thankful if u could offer me some help :)
As the worksheet index starts from 0 (not from 1), there is no sheet index that will equal the value of $nombreFeuille, so this code should be throwing and exception.
As you're not catching that exception anywhere in your code, it will never instantiate the writer, or save the file
Related
<?php
require_once("PHPExcel/Classes/PHPExcel.php");
require_once("PHPExcel/Classes/PHPExcel/Writer/Excel2007.php");
require_once("PHPExcel/Classes/PHPExcel/IOFactory.php");
$objPHPExcel = new PHPExcel();
$inputFileName = 'R1.xlsx';
$objPHPExcel = PHPExcel_IOFactory::load($inputFileName);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'HTML');
$objPHPExcel->setActiveSheetIndex(0);
$objWriter->save('php://output');
This is my code its good to get excel Sheet1 output from R1.xlsx file to browser. But R1.xlsx contain more than one sheets how to show them by link or vertically to show sheet2 and sheet3 data?
Thanks
PS.
I tried
$objPHPExcel->setActiveSheetIndex(X); by changing X value
By default, the HTML Writer will only generate output for a single worksheet
You can specify which sheet to write by calling
$objWriter->setSheetIndex(2);
specifying the individual sheet that you want to output
But you can also tell it to generate an output for all sheets instead using
$objWriter->writeAllSheets();
before the save
You can use a for loop, in each loop, output the content of each table.
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 am trying to open an existing excel file, modify some cells and save it. I am using Excel2007 for reader and writer.
The input file is about 1 MB large and it has few formulas, protected data and hidden rows and columns and worksheets which I do not modify.
I am able to load the data and read and write some values into it, which I check with various var_dumps in the code.
The problem is while saving it. It throws some fatal errors on timing outs and also if it writes the file the file size is bloated to 9.2 MB, which is okay if I can open it.
code snippet - nothing fancy.
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$objPHPExcel = $objReader->load($inputFile);
$objPHPExcel->setActiveSheetIndex(2);
$activeSheet = $objPHPExcel->getActiveSheet();
$currCell = $activeSheet->getCell("O3");
$cellValidation = $currCell->getDataValidation("O3");
$values = array();
if ($cellValidation->getShowDropDown() == true)
{
$values = $cellValidation->getFormula1();
$valArray = explode(",", $values);
$currCell->setValue($valArray[0]);
}
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter -> setPreCalculateFormulas(false);
$objWriter->save($outputFile);
I use MS Excel 2010 to open the resultant file but it just takes forever and has not opened it even once.
Please help me to troubleshoot this by giving me pointers as to where I should be looking.
Any help is greatly appreciated.
Instead of saving it to a file, save it to php://outputĀDocs:
$objWriter->save('php://output');
This will send it AS-IS to the browser.
You want to add some headersĀDocs first, like it's common with file downloads, so the browser knows which type that file is and how it should be named (the filename):
// We'll be outputting an excel file
header('Content-type: application/vnd.ms-excel');
// It will be called file.xls
header('Content-Disposition: attachment; filename="file.xls"');
// Write file to the browser
$objWriter->save('php://output');
First do the headers, then the save. For the excel headers see as well the following question: Setting mime type for excel document.
So the final code would have below lines -
// Save Excel 2007 file
#echo date('H:i:s') . " Write to Excel2007 format\n";
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
ob_end_clean();
// We'll be outputting an excel file
header('Content-type: application/vnd.ms-excel');
// It will be called file.xls
header('Content-Disposition: attachment; filename="file.xlsx"');
$objWriter->save('php://output');
I think this line:
ob_end_clean();
Should solve your problem.
Thanks!
There's a whole lot of reasons for that "bloat" and it very much depends on the actual data in the worksheet, but MS Excel itself uses a lot of different techniques to keep the filesize small, whereas PHPExcel writes a simple version of the OfficeOpenXML format.
For example, MS Excel looks at the string content of all cells, and stores the individual strings in a string table. If a string is used by two or more cells, there will only be a single entry in the string table. However, there's a performance overhead in checking if a string already exists in the string table, so PHPExcel doesn't perform that check but will duplicate entries in the string table. This means that it will create a large file because of the duplication, but keeps the save speed as fast as possible.
Similarly, MS Excel looks at all formulae, and if the formula is similar to an existing formula (with only a row/column offset difference) it will store it as a shared formula rather than a cell formula, so the actual formula data is only stored once. Again, PHPExcel won't perform this check, because it is a big performance overhead in the save, so it stores every formula as a cell formula rather than a shared formula.
And no, I can't explain why the file doesn't load in MS Excel 2010, nor will I be able to explain it without being able to run the whole thing through debug
I have an Excel file with 20 Sheets. Every sheet has 61 rows (one for title and 60 for the data).
I want to create a duplicate file, using only 2nd and last row from every sheet of the original file
So in my new file, I will have 40 rows in one sheet
I have tried PHPExcel, but none of the methods help me. Thanks
Using PHPExcel: reading the file is a logical first step, then loop through each worksheet and use the removeRow() method to delete the rows you don't want, then save the file.... pretty straightfoward.
require_once 'Classes/PHPExcel.php';
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$objPHPExcel = $objReader->load("myFileName.xlsx");
// Iterate through each of the 20 worksheets
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
// Remove rows 3-60 (58 rows starting from row 3)
// This will move the last row (61) up to row 3
$worksheet->removeRow(3,58);
// Remove row 1
$worksheet->removeRow(1);
}
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('myFileName.xlsx');
I am having a .xlsx file. In the .xlsx file there are 4 sheets "activity",
"performance", "store", "display".
I want to load only one sheet in the memory at a time and after adding data to
report write it. my code is below
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$worksheet_names = $objReader->listWorksheetNames('/tmp/ac.xlsx');
$objReader->setLoadSheetsOnly('store');
$objPHPExcel = $objReader->load('/tmp/ac.xlsx');
$objPHPExcel->setActiveSheetIndexByName('store');
$sheet = $objPHPExcel->getActiveSheet();
$max_row = $sheet->getHighestRow();
$sheet->setCellValue("A$max_row", "Data");
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->setPreCalculateFormulas(false);
$objWriter->save('/tmp/ac.xlsx');
$objPHPExcel->disconnectWorksheets();
unset($objPHPExcel);
the problem is it is writing on store sheet and deleting all the other sheets.
How do i make remain all the sheets while updating 'store sheet'
is there any function which will write one sheet at a time while
retaining the other sheets.
Only what you have loaded into the PHPExcel object will be placed into your new file.
The createWriter isn't editing the file and retaining the sheets, it's just writing a fresh copy of what you pass in to the file name you give it. In this case, it will overwrite the file because it is the same file that you have just opened to read from. So, you must take some caution to grab the entire workbook first, then alter what you want (from the entire worksheet). After that, write everything to the file with the new changes.
The code below should help you out with retaining the other sheets. To edit only specific sheets just place the sheet names you want to edit in the $editable_worksheets array. I was very descriptive with the comments, so hopefully they will clarify step by step how this is done.
// Load your PHPExcel class
require_once 'classes/PHPExcel/Classes/PHPExcel.php';
// Set variables for file location and type to make code more portable and
// less memory intensive
$file = '/tmp/ac.xlsx';
$file_type = 'Excel2007';
// Open file for reading
$objReader = PHPExcel_IOFactory::createReader($file_type);
// Take all exisiting worksheets in open file and place their names into an array
$worksheet_names = $objReader->listWorksheetNames($file);
// Array of worksheet names that should be editable
$editable_worksheets = array('activity', 'store');
// You will need to load ALL worksheets if you intend on saving to the same
// file name, so we will pass setLoadSheetsOnly() the array of worksheet names
// we just created.
$objReader->setLoadSheetsOnly($worksheet_names);
// Load the file
$objPHPExcel = $objReader->load($file);
// Loop through each worksheet in $worksheet_names array
foreach($worksheet_names as $worksheet_name) {
// Only edit the worksheets with names we've allowed in
// the $editable_worksheets array
if(in_array($worksheet_name, $editable_worksheets)) {
// Take each sheet, one at a time, and set it as the active sheet
$objPHPExcel->setActiveSheetIndexByName($worksheet_name);
// Grab the sheet you just made active
$sheet = $objPHPExcel->getActiveSheet();
// Grab the highest row from the current active sheet
$max_row = $sheet->getHighestRow();
// Set the value of column "A" in the last row to the text "Data"
$sheet->setCellValue("A" . $max_row, "Data");
}
// Foreach loop will repeat until all sheets in the workbook have been looped
// through
}
// Unset variables to free up memory
unset($worksheet_names, $worksheet_name, $sheet, $max_row);
// Prepare to write a new file
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, $file_type);
// Tell excel not to precalculate any formulas
$objWriter->setPreCalculateFormulas(false);
// Save the file
$objWriter->save($file);
// This must be called before unsetting to prevent memory leaks
$objPHPExcel->disconnectWorksheets();
// Again, unset variables to free up memory
unset($file, $file_type, $objReader, $objPHPExcel);
You're loading only a single sheet, so the PHPExcel object in memory contains only that sheet. When you save, you're overwriting the exoisting file with the workbook in memory (not editing the original file). If you want to save with the same name, and retain all four worksheet; you need to lpoad all four worksheets.