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";
Related
I am working with PhpSpreadsheet. When I use a formula that copies cell values, it adds to the formula the # symbol. This cause constant an error.
I need to prevent PhpSpreadsheet from adding this # symbol.
When I remove the #, the formula works perfectly.
//** Create a new Spreadsheet Object **//
$spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
$worksheet = $spreadsheet->getActiveSheet(); //get current active sheet (first sheet)
//** Set and load the reader **//
$inputFileName = $basePath;
$reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx(); // Create a new Reader of type xlsx
$reader->setReadDataOnly(false); // Keeping the style
$spreadsheet = $reader->load($inputFileName); // Load $inputFileName to a Spreadsheet Object
$spreadsheet->getActiveSheet()->fromArray($ufields, null, 'A8', true);
$attrs = $spreadsheet->getActiveSheet()->getCell("A10")->getFormulaAttributes();
$attrs['t'] = 'array';
$spreadsheet->getActiveSheet()->getCell("A10")->setFormulaAttributes($attrs);
$spreadsheet->getActiveSheet()->setCellValue("A10",'=IF(all_details!A8:I8<>"", all_details!A8:I8, "")');
$writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
$writer->setPreCalculateFormulas(false);
$writer->save($inputFileName);
//Export sheet code
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="'.$reportOriginalname.'"');
header('Cache-Control: max-age=0');
** I read and tried the solution suggested here, but it didn't work for me.
I have a 5 csv file that I will convert into an excel file.
I need this, coz I have to save them into my format like image and header.
Now, I am using phpexcel.
This is my code
public function parse_csv_to_excel() {
$gaug = FCPATH . "./assets/uploads/EGT_GAUG.CSV"; /*Will become a sheet named : gauge*/
$in = FCPATH . "./assets/uploads/EGT_IN.CSV"; /*Will become a sheet named : in_record*/
$out = FCPATH . "./assets/uploads/EGT_OUT.CSV"; /*Will become a sheet named : out_record*/
$stok = FCPATH . "./assets/uploads/EGT_STOK.CSV"; /*Will become a sheet named : stock_record*/
$strg = FCPATH . "./assets/uploads/EGT_STRG.CSV"; /*Will become a sheet named : storage_record*/
if (is_file($gaug) && is_file($in) && is_file($out) && is_file($stok) && is_file($strg)):
$this->load->library('excel');
$style_merge_cell = array(
'alignment' => array(
'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER
)
);
$this->excel->setActiveSheetIndex(0);
$this->excel->getDefaultStyle()->getFont()->setName('Arial')->setSize(10); //default font
$inputFileType = 'CSV';
$inputFileNames = array($in, $stok, $gaug, $strg, $out);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$inputFileName = array_shift($inputFileNames);
$objPHPExcel = $objReader->load($inputFileName);
$objPHPExcel->getActiveSheet()->setTitle(pathinfo($inputFileName, PATHINFO_BASENAME));
foreach ($inputFileNames as $sheet => $inputFileName) {
$objReader->setSheetIndex($sheet + 1);
$objReader->loadIntoExisting($inputFileName, $objPHPExcel);
$objPHPExcel->getActiveSheet()->setTitle(pathinfo($inputFileName, PATHINFO_BASENAME));
}
$loadedSheetNames = $objPHPExcel->getSheetNames();
foreach ($loadedSheetNames as $sheetIndex => $loadedSheetName) {
$objPHPExcel->setActiveSheetIndexByName($loadedSheetName);
$this->excel->getActiveSheet()->setTitle('Movement In');
$this->excel->createSheet();
$this->excel->getActiveSheet()->getPageSetup()->setPaperSize(PHPExcel_Worksheet_PageSetup::PAPERSIZE_A4);
$this->excel->getActiveSheet()->getDefaultRowDimension()->setRowHeight(-1);
$this->excel->getActiveSheet()->getColumnDimension('A')->setWidth(1.29);
$logo = new PHPExcel_Worksheet_Drawing();
$logo->setPath('./assets/img/logo_tras_excel.png');
$logo->setWidth(325);
$logo->setHeight(59);
$logo->setCoordinates('B2');
$logo->setWorksheet($this->excel->getActiveSheet());
$this->excel->getActiveSheet()->setCellValue('B6', 'To');
$this->excel->getActiveSheet()->setCellValue('B7', 'ATTN');
$this->excel->getActiveSheet()->setCellValue('B8', 'Customer');
$this->excel->getActiveSheet()->setCellValue('B9', 'From');
$this->excel->getActiveSheet()->setCellValue('B10', 'Activity Date');
$this->excel->getActiveSheet()->mergeCells('B12:Q12');
$this->excel->getActiveSheet()->setCellValue('B12', 'EAGLETAINER DAILY MOVEMENT REPORT ');
$this->excel->getActiveSheet()->getStyle('B12')->applyFromArray($style_merge_cell);
$this->excel->getActiveSheet()->setCellValue('B14', 'Subject');
$this->excel->getActiveSheet()->setCellValue('D14', ': MOVE IN');
$sheetData = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
$this->excel->getActiveSheet()->fromArray($sheetData, NULL, 'B16');
}
$filename = 'Daily report.xls'; //save our workbook as this file name
header('Content-Type: application/vnd.ms-excel'); //mime type
header('Content-Disposition: attachment;filename="' . $filename . '"'); //tell browser what's the file name
header('Cache-Control: max-age=0'); //no cache
//save it to Excel5 format (excel 2003 .XLS file), change this to 'Excel2007' (and adjust the filename extension, also the header mime type)
//if you want to save it as .XLSX Excel 2007 format
$objWriter = PHPExcel_IOFactory::createWriter($this->excel, 'Excel5');
//force user to download the Excel file without writing it to server's HD
$objWriter->save('php://output');
else :
echo " ONE OF FILE IS NOT FOUND";
endif;
}
Please, advise if my case :
How created a sheet that named like that I need of the top my code
I have 5 files, but the sheet was created is six.
Now, the csv is written just in first sheet with all element from array based 5 of csv files, the others is not.
Thanks,
Please Advise
I'm losing time as hell using this PHPExcel lib.
My code is widely inspired from models which are available in the lib.
+The mission is :
-To read an *.xls file with PHP
-Display it in a navigator in HTML
For the moment, I just can read the file successfully (with a "createReader" method of PHPExcel_IOFactory instance). But for the HTML display, I'm in a pretty good crap. At attempt of code correction gives me this error:
" Fatal error: Uncaught exception 'PHPExcel_Calculation_Exception' with
message 'Réalisé S03!P374 -> Réalisé S03!P374 -> Formula Error:
Unexpected ,' "
Here is the code :
<?phperror_reporting(E_ALL);
set_time_limit(0);
date_default_timezone_set('Europe/London');
/** Include path **/
set_include_path(get_include_path() . PATH_SEPARATOR . '../../../Classes/');
/** PHPExcel_IOFactory */
include 'PHPExcel/IOFactory.php';
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>PHPExcel Reader Example #02</title>
</head>
<body>
<h1>Chargement fichier Facturation</h1>
<?php
$inputFileName = '../Docs_PDC/FACTURATION_Janvier.xls';
echo 'Loading file ',pathinfo($inputFileName,PATHINFO_BASENAME),' using PHPExcel_Reader_Excel5<br />';
$objReader = new PHPExcel_Reader_Excel5();
// $objReader = new PHPExcel_Reader_Excel2007();
// $objReader = new PHPExcel_Reader_Excel2003XML();
// $objReader = new PHPExcel_Reader_OOCalc();
// $objReader = new PHPExcel_Reader_SYLK();
// $objReader = new PHPExcel_Reader_Gnumeric();
// $objReader = new PHPExcel_Reader_CSV();
$objPHPExcel = $objReader->load($inputFileName);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'HTML');
$objWriter->save('Facturation.html');
echo '<hr />';
$sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
var_dump($sheetData);
$filename = "DownloadReport";
$table = $_POST['table'];
// save $table inside temporary file that will be deleted later
$tmpfile = tempnam(sys_get_temp_dir(), 'html');
file_put_contents($tmpfile, $table);
// insert $table into $objPHPExcel's Active Sheet through $excelHTMLReader
$objPHPExcel = new PHPExcel();
$excelHTMLReader = PHPExcel_IOFactory::createReader('HTML');
$excelHTMLReader->loadIntoExisting($tmpfile, $objPHPExcel);
$objPHPExcel->getActiveSheet()->setTitle('Facturation'); // Change sheet's title if you want
unlink($tmpfile); // delete temporary file because it isn't needed anymore
header('Content-Type: application/vnd.openxmlformats- officedocument.spreadsheetml.sheet'); // header for .xlxs file
header('Content-Disposition: attachment;filename='.$filename); // specify the download file name
exit;
?>
<body>
If someone has any idea I'll eternally grateful to him (or her ;) )
I dug a little more on this, and i noticed that: the exception is raised because
PHPExcel tries to resolve a formula with an Excel reference value (like "P$7") in argument. And the referenced value is not a number, it's just a column name.
So, Is it possible to disable PHPExcel's formula solving in some fields ? Or is there any other way to get around this ?
this is my code i want to attach this file and send it and the values are numerical variables that in excel file i use them to drow a chart
it dosen't work at all ,
my boss is mad at me , Help
let me explain more . i have to attach an excel file {which contains 4 numbers that are a test result and draw a chart } I've done the test i have the result, i have done sending with attachment but i can't make the file .
require_once '../Classes/PHPExcel.php';
$fileType = 'Excel2007';
$fileName = 'Result.xlsx';
// Read the file
$objReader = PHPExcel_IOFactory::createReader($fileType);
$objPHPExcel = $objReader->load($fileName);
// Change the file
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, $fileType);
$objSheet = $objPHPExcel->setActiveSheetIndex(0);
objSheet->getCell('A2')->setValue($SumY );
objSheet->getCell('B2')->setValue($SumR );
objSheet->getCell('C2')->setValue($SumB );
objSheet->getCell('D2')->setValue($SumG );
// Write the file
$objWriter->save('Result.xlsx');
Tell PHPExcel that you want to include charts when reading and writing
Assuming that the chart is defined in your template
require_once '../Classes/PHPExcel.php';
$fileType = 'Excel2007';
$fileName = 'Result.xlsx';
// Read the file (including chart template)
$objReader = PHPExcel_IOFactory::createReader($fileType);
$objReader->setIncludeCharts(TRUE);
$objPHPExcel = $objReader->load($fileName);
// Change the file
$objSheet = $objPHPExcel->setActiveSheetIndex(0);
$objSheet->getCell('A2')->setValue($SumY );
$objSheet->getCell('B2')->setValue($SumR );
$objSheet->getCell('C2')->setValue($SumB );
$objSheet->getCell('D2')->setValue($SumG );
// Write the file (including chart)
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, $fileType);
$objWriter->setIncludeCharts(TRUE);
$objWriter->save('Result.xlsx');
If the chart isn't defined in your template, then you need to create it in your code
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.