1

I want to convert Excel files (.xls) into CSV file (.csv) with a script PHP ? I tried many codes but it didn't work like this one ! No errors appear but it wont work Any idea or any other lines of codes that I can try ?

<?php

echo("it works");
require_once '../batchs/Classes/PHPExcel/IOFactory.php';

$inputFileType = 'Excel5';
$inputFileName = '../public/aixstream/stock.xls';

$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');
}
?>

Thank you

pnuts
  • 58,317
  • 11
  • 87
  • 139

1 Answers1

1

As already stated in this answer, you can use the PHP-ExcelReader function to read the xls file. After that, you may easily convert it into CSV (or any other other format) using the following code, also available here.

Reading the xls file

//You will obviously need to import the function
//by downloading the file from the link above.

$reader=new Spreadsheet_Excel_Reader(); //Instantiate the function
$reader->setUTFEncoder('iconv'); // Set Encoder
$reader->setOutputEncoding('UTF-8'); // Set Output Encoding Type
$reader->read($filename); // Read the xls file

Data Output

/***
* Information about sheets is stored in boundsheets variable.
* This code displays each sheet's name.
***/
foreach ($reader->boundsheets as $k=>$sheet) //Run loop for all sheets in the file
 {
    echo "\n$k: $sheet"; 
 }

//Now just save the data in the array as csv

/***
* Data of the sheets is stored in sheets variable.
* For every sheet, a two dimensional array holding table is created.
* This code saves all data to CSV file.
***/
 foreach($reader->sheets as $k=>$data) // Run loop for all items.
 {
    echo "\n\n ".$reader->boundsheets[$k]."\n\n"; //Print Title

    foreach($data['cells'] as $row) // Loop for all items
    {
        foreach($row as $cell) // Loop for every cell
        {
            echo "$cell".","; //Add a comma after each value
        }
    }
 }

//It works! :D
Community
  • 1
  • 1
Acharya Anurag
  • 671
  • 6
  • 23
  • Can you please explain to me the code ? you will find my answer and the code below because it's too long for a comment – Safa ben Mansour Aug 20 '15 at 08:42
  • 1
    Yes, your code below seems just fine when I look at it, though I have not checked by running it. Have you tried running it? Don't forget, you need to include the function I gave a link to in the answer for this to work. I have edited my answer to include comments explaining how the code works. The detailed explanation, as I already stated, is also available [in this link](http://www.ustrem.org/en/articles/reading-xls-with-php-en/). – Acharya Anurag Aug 20 '15 at 09:50