Convert excel to csv in php

When working with data import and export for example, file formats like csv and excel are commonly used. Data can be exported to csv format and imported elsewhere. Also data might be entered manually in an excel file and then imported in the database. So there might be a need to convert excel files to csv format, so that they can be parsed easily and processed.

Converting excel files to csv is very easily done using a popular library called PHPExcel. Lets take a look at an example right away.

/**
	Convert excel file to csv
*/

//Various excel formats supported by PHPExcel library
$excel_readers = array(
	'Excel5' , 
	'Excel2003XML' , 
	'Excel2007'
);

require_once('lib/PHPExcel/PHPExcel.php');

$reader = PHPExcel_IOFactory::createReader('Excel5');
$reader->setReadDataOnly(true);

$path = 'data.xls';
$excel = $reader->load($path);

$writer = PHPExcel_IOFactory::createWriter($excel, 'CSV');
$writer->save('data.csv');

echo 'File saved to csv format';

The above piece of code will convert the file data.xls to csv format and save it. PHPExcel can read various versions of excel format like 2000, 2003 and 2007. So it needs to be told the format of the excel file that is being converted.
The above technique has some limitations. For example it only converts the first sheet of the excel file to csv. And any additional excel based formatting is lost. However this is a limitation of the csv format itself so does not matter.

PHPExcel can be downloaded from

http://phpexcel.codeplex.com/







Last Updated On : 11th March 2013

Subscribe to get updates delivered to your inbox

2 Comments + Add Comment

  • I work on backend where I have found myself to feed large set of data provided as excel file. Your script is very useful for converting it to csv. I have found another good php resource which imports data from csv file into mysql db. You can check it out here http://www.kodingmadesimple.com/2015/07/import-csv-file-into-mysql-database-php-script.html

  • I have get result but don’t get data properly,
    Like in my excel file date is:1/14/2014
    But It will display date as:41653.

    Could you please solve this issue.

    Thank you in advance.

Leave a comment