phpexcel and csv save to zip using CI zip library - php

i want to export some data with xlsx and csv format. recently i create some function to do it. and my idea is :
1.save the xlsx and the csv in the temp,
2. add it to the zip library
3. download it.
i have tried to make some functions, and the csv is show an output in the zip, but the excel is not show any output. there is no error, but the excel file doesn't saved at the zip file
Here is my function for creating the excel file
public function createExcel($id){
$excel = PHPExcel_IOFactory::load('C:\xampp\htdocs\api-priadi\ContohExcel.xlsx');
$excel->setActiveSheetIndex(0);
$resultExcel = $this->AdminM->getDataExcel($id);
$rows = 3;
foreach ($resultExcel->result() as $rowExcel){
$excel->getActiveSheet()->setCellValueByColumnAndRow(0,$rows,$rowExcel->id);
$excel->getActiveSheet()->setCellValueByColumnAndRow(1,$rows,$rowExcel->name);
$rows++;
}
$objWriter = PHPExcel_IOFactory::createWriter($excel, 'Excel2007');
$this->zip->add_data('excel'.date('').date('Y_M_d_H_i_s').'.xlsx',$objWriter->save('assets/Haha.xlsx'));
}
and here is the function to create the csv file,
public function createCSV($id){
$csv = fopen("php://temp", "rw");
fputcsv($csv, array('Name', 'Email', 'Birthdate'));
$dataCSV = $this->AdminM->getDataCSV($id);
foreach ($dataCSV as $row){
fputcsv($csv, $row);
}
global $fileCSV;
$fileCSV = stream_get_contents($csv,-1,0);
fclose($csv);
$this->zip->add_data('csv'.date('').date('Y_M_d_H_i_s').'.csv',$fileCSV);
}
and here the code to asssembled the function and download it at the same time.
public function download(){
$id = $this->input->post('id');
$this->createCSV($id);
$this->createExcel($id);
$this->zip->download('testing.zip');
}
what i expect is to download the csv and the excel at the same time

Try to save the xls file first, then load it using PHPExcel_IOFactory::load, then pass the loaded xls file as the zip parameter :
public function createExcel($id){
$excel = PHPExcel_IOFactory::load('C:\xampp\htdocs\api-priadi\ContohExcel.xlsx');
$excel->setActiveSheetIndex(0);
$resultExcel = $this->AdminM->getDataExcel($id);
$rows = 3;
foreach ($resultExcel->result() as $rowExcel){
$excel->getActiveSheet()->setCellValueByColumnAndRow(0,$rows,$rowExcel->id);
$excel->getActiveSheet()->setCellValueByColumnAndRow(1,$rows,$rowExcel->name);
$rows++;
}
$xls_name = 'assets/Haha.xlsx';
$objWriter = PHPExcel_IOFactory::createWriter($excel, 'Excel2007');
$objWriter->save($xls_name);
$objPHPExcel = PHPExcel_IOFactory::load($xls_name);
$this->zip->add_data('excel'.date('').date('Y_M_d_H_i_s').'.xlsx', $objPHPExcel);
}

Related

PhpSpreadSheet: How to save Workbook sheets in individual CSV files

I'm using PhpSpreadSheet and I need to save the sheets contained in a workbook as individual CSV files.
I've tried to use $reader->setLoadAllSheets(); but at the end I always have a single CSV file containing the first sheet of the workbook.
Here's an example of my code:
$excel = 'excelfile.xlsx';
$name = 'newCsvName';
//Read the file
$reader = new Xlsx();
$reader->setReadDataOnly(true);
$reader->setLoadAllSheets();
$spreadsheet = $reader->load($excel);
//Write the CSV file
$writer = new \PhpOffice\PhpSpreadsheet\Writer\Csv($spreadsheet);
$writer->setDelimiter(";");
$csvPath = 'csv_files/' . $dir . '/' . $name .'.csv';
$writer->save($csvPath);
This is how I solved it.
I first load every sheet contained into the excel file and then save a new CSV file with the info. I'm sure there should be a better way, but it works fine.
$excel = 'excelfile.xlsx';
$name = 'newCsvName';
$reader = new Xlsx();
$reader->setReadDataOnly(true);
//Get all sheets in file
$sheets = $reader->listWorksheetNames($excel);
//Loop for each sheet and save an individual file
foreach($sheets as $sheet){
//Load the file
$spreadsheet = $reader->load($excel);
//Write the CSV file
$writer = new \PhpOffice\PhpSpreadsheet\Writer\Csv($spreadsheet);
$writer->setDelimiter(";");
$csvPath = 'csv_files/' . $dir . '/' . $name.'_'.$sheet.'.csv';
$writer->save($csvPath);
}
The answer above is missing a vital line:
$reader->setLoadSheetsOnly([$sheet]);
This makes the reader load the specific sheet which then allows the loop to open the specific sheet and write it to the CSV, otherwise you will find this code creates each sheet name but with the contents from the first sheet of the document.
$excel = 'excelfile.xlsx';
$name = 'newCsvName';
$reader = new Xlsx();
$reader->setReadDataOnly(true);
//Get all sheets in file
$sheets = $reader->listWorksheetNames($excel);
//Loop for each sheet and save an individual file
foreach($sheets as $sheet){
//Load the file
$reader->setLoadSheetsOnly([$sheet]);
$spreadsheet = $reader->load($excel);
//Write the CSV file
$writer = new \PhpOffice\PhpSpreadsheet\Writer\Csv($spreadsheet);
$writer->setDelimiter(";");
$csvPath = 'csv_files/' . $dir . '/' . $name.'_'.$sheet.'.csv';
$writer->save($csvPath);
}

Clear the excel file after download it to reuse in PHPExcel

I am creating excel file with single worksheet using PHPExcel.
I have managed to do this but the issue came after when I created it ones then it didn't get clear so when I am creating it again the the previous data came along with the new data.
So I am just want to clear the excel file before using it again.
Here is the code:
require_once APPPATH.'third_party/PHPExcel.php';
require_once APPPATH.'third_party/PHPExcel/IOFactory.php';
//Getting Data form database
$bTob_gstdata = $this->reports_model->get_bTob_gstdata($date_from, $date_to);
//Sample Excel File (which is clear already Just contain the structure)
$filename = 'assets/btob_base_excel.xls';
$objPHPExcel = PHPExcel_IOFactory::load($filename);
echo $filetype = PHPExcel_IOFactory::identify($filename);
$excel2 = PHPExcel_IOFactory::createReader($filetype);
$excel2 = $excel2->load('assets/btob_base_excel.xls'); // Empty Sheet
$excel2->setActiveSheetIndex(0);
$t=0;
$total_invoice_count = 0;
$recipients_count = array();
$invoice_count = array();
for($k=5;$k<(count($bTob_gstdata)+5);$k++)
{
//Adding Data in Excel WorkSheet
$excel2->getActiveSheet()
->setCellValue('A'.$k, $bTob_gstdata[$t]["dist_gstin"]);
$t++;
}
$excel2->getActiveSheet()->setCellValue('A3', (count($recipients_count)));
$excel2->getActiveSheet()->setCellValue('B3', (count($invoice_count)));
$excel2->getActiveSheet()->setCellValue('D3', '=SUM(D5:D'.(count($bTob_gstdata)+5).')');
$excel2->getActiveSheet()->setCellValue('J3', '=SUM(J5:J'.(count($bTob_gstdata)+5).')');
$excel2->setActiveSheetIndex(0);
$objWriter = PHPExcel_IOFactory::createWriter($excel2, $filetype);
$objWriter->save('btocl_gst_report.xls'); //Saving the excel file
header("location:".base_url("btob_gst_report.xls")); // Downloading the excel file
I want to clear the created excel file to Reuse

PHPExcel CSV to XLSX

I have a problem converting file feom CSV to XLSX format:
Index.php
<?php
if (!isset($_FILES["file"]))
{
?>
<html>
<body>
<h1>Convert CSV to XLSX</h1>
<form action="index.php" method="post" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="submit"/>
</form>
</body>
</html>
<?php
exit;
}
//obtain PHPExcel from http://phpexcel.codeplex.com
require_once('Classes\PHPExcel.php');
require_once('CSVToExcelConverter.php');
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"];
exit;
}
try
{
header('Content-type: application/ms-excel');
header('Content-Disposition: attachment; filename='.'example.xlsx');
CSVToExcelConverter::convert($_FILES['file']['tmp_name'], 'php://output');
} catch(Exception $e) {
echo $e->getMessage();
}
CSVToExcelConverter.php
class CSVToExcelConverter
{
/**
* Read given csv file and write all rows to given xls file
*
* #param string $csv_file Resource path of the csv file
* #param string $xls_file Resource path of the excel file
* #param string $csv_enc Encoding of the csv file, use utf8 if null
* #throws Exception
*/
public static function convert($csv_file, $xls_file, $csv_enc=null) {
//set cache
$cacheMethod = PHPExcel_CachedObjectStorageFactory::cache_to_phpTemp;
PHPExcel_Settings::setCacheStorageMethod($cacheMethod);
//open csv file
$objReader = new PHPExcel_Reader_CSV();
if ($csv_enc != null)
$objReader->setInputEncoding($csv_enc);
$objPHPExcel = $objReader->load($csv_file);
$in_sheet = $objPHPExcel->getActiveSheet();
//open excel file
$objPHPExcel = new PHPExcel();
$out_sheet = $objPHPExcel->getActiveSheet();
//row index start from 1
$row_index = 0;
foreach ($in_sheet->getRowIterator() as $row) {
$row_index++;
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(false);
//column index start from 0
$column_index = -1;
foreach ($cellIterator as $cell) {
$column_index++;
$out_sheet->setCellValueByColumnAndRow($column_index, $row_index, $cell->getValue());
}
}
//write excel file
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
$objWriter->save($xls_file);
}
}
CSV File format: CSV file opened with Excel
xlsx file I get after conversion
Basicaly I would like to get output similar to original csv file, but in xmlx format, how to do that?
The "default" separator for reading a CSV file in PHPExcel is a comma (,). Your CSV file is using something other than a comma - perhaps a tab ("\t"), which is also commonly used for such files).
If the values isn't a comma (and we can't tell from an image of the file viewed in MS Excel) then you have to tell PHPExcel explicitly what that separator is before loading.
e.g.
$objReader->setDelimiter("\t");

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.

Categories