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);
}
Related
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);
}
I want to read the data of .xlsx or .xls file in codeigniter. I have read the other questions related it but nothing works. I have used phpexcel, reader but with no luck. In my project i give the option to upload excel file then i want to read the data and insert it in the database.
Now i am using phpExcel library I have wrote:
$this->load->library('excel');
$reader= PHPExcel_IOFactory::createReader('Excel2007');
$reader->setReadDataOnly(true);
$path=(FCPATH.'uploads/productfile/'.$_FILES['upload_file']['name']);
$excel=$reader->load($path);
$sheet=$excel->setActiveSheetIndex(0);
for($i=0;$i<=1000;$i++)
{
$col1= $sheet->getCellByColumnAndRow(0,$i)->getValue();
$col2= $sheet->getCellByColumnAndRow(1,$i)->getValue();
$col3= $sheet->getCellByColumnAndRow(2,$i)->getValue();
var_dump($col1);
}
but it display :
Uncaught exception 'PHPExcel_Exception' with message 'You tried to set
a sheet active by the out of bounds index: 0. The actual number of
sheets is 0 Please give me some example code.
The error
Please give me some example code:
Try this :
$sheet = $excel->getActiveSheet()->toArray(null,true,true,true);
This will return you an array of the current active sheet.Hope this helps.
This error is caused by a wrong initialization of the PHPexcel reader functionalities I suppose.
I usually do something like this to get the data from an excel:
require_once '../Classes/PHPExcel/IOFactory.php';
$filename = '../uploads/product/abc.xls';
$objPHPExcel = PHPExcel_IOFactory::load($filename);
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
$worksheetTitle = $worksheet->getTitle();
$highestRow = $worksheet->getHighestRow(); // e.g. 10
$highestColumn = $worksheet->getHighestColumn(); // e.g 'F'
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
$nrColumns = ord($highestColumn) - 64;
$total_rows = $highestRow-1;
for ($row = 2; $row <= $highestRow; ++ $row) {
//id
$cell = $worksheet->getCellByColumnAndRow(0,$row);
$id = $cell->getValue();
if(is_null($id)){$id = '#';}
}
Thanks to all for your suggestion:
I got the solution :
$file_data = $this->upload->data();
$file_path = './uploads/productfile/'.$file_data['file_name'];
include 'Classes/PHPExcel/IOFactory.php';
$inputFileName = $file_path;
$objPHPExcel = PHPExcel_IOFactory::load($inputFileName);
$allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
$arrayCount = count($allDataInSheet); // Here get total count of row in that Excel sheet
for($i=2;$i<=$arrayCount;$i++)
{
'product'=$allDataInSheet[$i]["C"],
'brand'=$allDataInSheet[$i]["I"],
'standard'=$allDataInSheet[$i]["J"],
}
This extension of PHPExcel_IOFactory has issues with symbols like ™ Trademark, Copy Right, Degree etc.
You can't read a particular block if it contains such special characters.
This code segment works for me,
$this->load->library('excel');
$reader= PHPExcel_IOFactory::createReader('Excel2007');
$reader->setReadDataOnly(true);
$path= "./media/customer_exports/data-1558003506.xlsx";
$excel=$reader->load($path);
$sheet = $excel->getActiveSheet()->toArray(null,true,true,true);
$arrayCount = count($sheet);
for($i=2;$i<=$arrayCount;$i++)
{
echo $sheet[$i]["A"].$sheet[$i]["B"].$sheet[$i]["C"];
}
Error Shows
->Warning: ZipArchive::getFromName(): Invalid or unitialized Zip object
When uploading files, and reading excel files, sometimes it shows that error message.
This is my code:
$pasFile = $_FILES['inputFileLocation']['name'];
$target_path = basename($pasFile);
if(move_uploaded_file($_FILES["inputFileLocation"]["tmp_name"], $target_path)){
require_once '../template/PHPExcel/Classes/PHPExcel.php';
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$worksheet_names = $objReader->listWorksheetNames($pasFile);
$countWorksheet = count($worksheet_names);
$optionSheetName = "<option></option>";
for($x = 0;$x < $countWorksheet;$x++){
$optionSheetName = $optionSheetName."<option value='".$worksheet_names[$x]."'>".$worksheet_names[$x]."</option>";
}
}
Thank you in advance! :)
My mistake! The file that I was uploading had different types of excel format.
This code now works by identifying the format then passing it to the create reader.
Many thanks to Mr. Baker!
I added this codes:
$inputFileType = PHPExcel_IOFactory::identify($pasFile);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
Resulting to this one:
$pasFile = $_FILES['inputFileLocation']['name'];
$target_path = basename($pasFile);
if(move_uploaded_file($_FILES["inputFileLocation"]["tmp_name"], $target_path)){
require_once '../template/PHPExcel/Classes/PHPExcel.php';
$inputFileType = PHPExcel_IOFactory::identify($pasFile);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$worksheet_names = $objReader->listWorksheetNames($pasFile);
$countWorksheet = count($worksheet_names);
$optionSheetName = "<option></option>";
for($x = 0;$x < $countWorksheet;$x++){
$optionSheetName = $optionSheetName."<option value='".$worksheet_names[$x]."'>".$worksheet_names[$x]."</option>";
}
}
identify() first before createReader()...
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.