简体   繁体   中英

PHP - Read excel file

I want to read an Excel file with PHP row by row because reading the entire file at once cause memory overflow.

I have searched a lot, but no luck until now.

I think PHPExcel library can read chunks of an excel file, when you implement the filter class, but each time it gets this chunk it reads the entire file, which is impossible in huge .xls files because of the time it will take.

Any help ?

This may be something that is totally out of question, but from the information that I get from your question the following seems like an obvious option, at least something to consider ...

I get the impression that this is a really big file that needs to be accessed often. So, I would just try to import its data in a database.

  • I guess there is no need to explain that databases are masters in performance and caching.
  • And it is still possible to export the contents of the database to an excel file afterwards.
  • MySql works great with PHP and is certainly easier to access than an excel file. Most php hosting providers offer a MySql database by default with a PhpMyAdmin management tool.

How to do it:

  • If you have PhpMyAdmin installed, then you can follow these simple steps .
  • If you have command-line access to the server then you can even import the file from commandline directly to a MySql database.

If the only thing you need from your read Excel file is data, here is my way to read huge Excel files :

I install gnumeric on my server, ie with debian/ubuntu : apt-get install gnumeric

Then the php calls to read my excel file and store it into a two dimensionnal data array are incredibly simple (dimensions are rows and cols) :

system("ssconvert \"$excel_file_name\" \"temp.csv\"");
$array = array_map("str_getcsv", file("temp.csv"));

Then I can do what I want with my array. This takes less than 10 seconds for a 10MB large xls file, the same time I would need to load the file on my favorite spreadsheet software !

For very huge files, you should use fopen() and file_getcsv() functions and do what you have to do without storing data in a huge array to avoid storing the whole csv file in memory with the file() function. This will be slower, but will not eat all your server's memory !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM