PhpSpreadSheet: How to save Workbook sheets in individual CSV files - php

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);
}

Related

Save File in PHPExcel

Is it posibble to save existing file with out creating the writer object in PHPExcel?
$filename = 'test.xlsx';
$phpExcel = PHPExcel_IOFactory::load($filename);
$phpExcel->save($filename);

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 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.

PHP code can insert image to excel file and open it correctly in MS Excel?

I already have a document of excel and I want to use php to insert an image to that excel.
Is it possible to do that? How to implement it (code)?
Thanks,
$fileType = 'Excel2007';
$fileName = 'test.xlsx';
// Load the workbook
$objPHPExcelReader = PHPExcel_IOFactory::createReader($fileType);
$objPHPExcel = $objPHPExcelReader->load($fileName);
// Add an image to the worksheet
$objDrawing = new PHPExcel_Worksheet_Drawing();
$objDrawing->setName('My Image');
$objDrawing->setDescription('The Image that I am inserting');
$objDrawing->setPath('./images/myImage.png');
$objDrawing->setCoordinates('B2');
$objDrawing->setWorksheet($objPHPExcel->getActiveSheet());
// Save the workbook
$objPHPExcelWriter = PHPExcel_IOFactory::createWriter($objPHPExcel,$fileType);
$objPHPExcelWriter->save($fileName);

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