31
votes

Can anyone guide me how to convert XLS to CSV using PHP?

I have excel spread sheet which contains a list of documents, I want to convert this with CSV format using PHP.

5
Excel has a CSV export option. Is it not feasible to have your users use that? (Just thinking of the least work-intensive way...) - Pekka
A CSV file can only contain one table of data, so it's not possible to convert one XLS file with multiple tables into one CSV file. - hakre
Sure you can, and it's a worksheet you refer to. it will export the last worksheet by default. - Glenn Plas

5 Answers

12
votes

Probably you can start reading a XLS using PHP.

Then, using the main logic to output what you want (csv in your case).

Good luck,

22
votes

This will surely work,

require_once 'Classes/PHPExcel/IOFactory.php';

$inputFileType = 'Excel5';
$inputFileName = 'YOUR_EXCEL_FILE_PATH';

$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcelReader = $objReader->load($inputFileName);

$loadedSheetNames = $objPHPExcelReader->getSheetNames();

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcelReader, 'CSV');

foreach($loadedSheetNames as $sheetIndex => $loadedSheetName) {
    $objWriter->setSheetIndex($sheetIndex);
    $objWriter->save($loadedSheetName.'.csv');
}

Hope this helps...

16
votes

Rewrite the code provided by @Rajat Modi using PhpSpreadsheet library due to PHPExcel is deprecated.

https://github.com/PHPOffice/PhpSpreadsheet

https://phpspreadsheet.readthedocs.io/en/develop/

<?php 

require 'vendor\autoload.php';

use \PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use \PhpOffice\PhpSpreadsheet\Writer\Csv;

$xls_file = "Example.xlsx";

$reader = new Xlsx();
$spreadsheet = $reader->load($xls_file);

$loadedSheetNames = $spreadsheet->getSheetNames();

$writer = new Csv($spreadsheet);

foreach($loadedSheetNames as $sheetIndex => $loadedSheetName) {
    $writer->setSheetIndex($sheetIndex);
    $writer->save($loadedSheetName.'.csv');
}
5
votes

You can use the php library PHPExcel to read the excel file, and just loop over the rows and cells and just write the data out to a csv file?

0
votes

This will work. Install Spout

<?php 
require 'vendor\autoload.php';
use Box\Spout\Writer\Common\Creator\WriterEntityFactory;
use Box\Spout\Reader\Common\Creator\ReaderEntityFactory;

$writer = WriterEntityFactory::createCSVWriter();
$reader = ReaderEntityFactory::createXLSXReader();
$writer->openToFile("Output CSV path");
$reader->open("Input XSLX path");

foreach ($reader->getSheetIterator() as $sheet) {
   foreach ($sheet->getRowIterator() as $row) {
       $writer->addRow($row);
   }
}

$writer->close();
$reader->close();