Home Backend Development PHP Tutorial Solution to memory overflow error when phpExcel exports large amounts of data_PHP Tutorial

Solution to memory overflow error when phpExcel exports large amounts of data_PHP Tutorial

Jul 13, 2016 pm 05:06 PM
phpexcel use Memory Appear Method import Export us data overflow solve mistake

We often use phpExcel to import or import xls files, but if the exported data is relatively large at one time, a memory overflow error will occur. Let me summarize the solutions below.

phpExcel saves the read cell information in memory, we can pass

The code is as follows Copy code
 代码如下 复制代码

PHPExcel_Settings::setCacheStorageMethod()

PHPExcel_Settings::setCacheStorageMethod()

To set different caching methods, the purpose of reducing memory consumption has been achieved!

1. Serialize the cell data and save it in memory
 代码如下 复制代码

PHPExcel_CachedObjectStorageFactory::cache_in_memory_serialized; 

The code is as follows Copy code

PHPExcel_CachedObjectStorageFactory::cache_in_memory_serialized;

 代码如下 复制代码

PHPExcel_CachedObjectStorageFactory::cache_in_memory_gzip; 

2. Serialize the cells and then Gzip compress them, then save them in memory

The code is as follows Copy code
PHPExcel_CachedObjectStorageFactory::cache_in_memory_gzip;
 代码如下 复制代码

PHPExcel_CachedObjectStorageFactory::cache_to_discISAM;

3. Caching in temporary disk files may be slower

The code is as follows Copy code
 代码如下 复制代码

PHPExcel_CachedObjectStorageFactory::cache_to_phpTemp; 

PHPExcel_CachedObjectStorageFactory::cache_to_discISAM;

4. Save in php://temp

The code is as follows Copy code
PHPExcel_CachedObjectStorageFactory::cache_to_phpTemp;


5. Save in memcache

PHPExcel_CachedObjectStorageFactory::cache_to_memcache

 代码如下 复制代码

$cacheMethod = PHPExcel_CachedObjectStorageFactory:: cache_to_phpTemp; 
$cacheSettings = array( ' memoryCacheSize '  => '8MB' 
                ); 
PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings); 

Example: Medium 4:
The code is as follows Copy code
$cacheMethod = PHPExcel_CachedObjectStorageFactory:: cache_to_phpTemp; $cacheSettings = array( ' memoryCacheSize ' => '8MB' ); PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);

Type 5:

The first method, you can consider generating multiple sheets. You don’t need to generate multiple excel files. Calculate how many rows each sheet exports based on the total amount of your data. The following is how PHPExcel generates multiple sheets:
The code is as follows
 代码如下 复制代码

$cacheMethod = PHPExcel_CachedObjectStorageFactory::cache_to_memcache; 
$cacheSettings = array( 'memcacheServer'  => 'localhost', 
                        'memcachePort'    => 11211, 
                        'cacheTime'       => 600 
                      ); 
PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);

Copy code

$cacheMethod = PHPExcel_CachedObjectStorageFactory::cache_to_memcache;

$cacheSettings = array( 'memcacheServer' => 'localhost',

‘memcachePort’ => 11211,

'cacheTime' => 600
 代码如下 复制代码

$sheet = $objPHPExcel->getActiveSheet(); 

$sheet->setCellValue('A1',$x);  

$sheet->setCellValue('B1',$y);

);

PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);

 代码如下 复制代码

export to Excel 

$('#export').click(function() {  

    $.ajax({  

        url: "export.php",   

        data: getData(),  //这个地方你也可以在php里获取,一般读数据库  

        success: function(response){  

            window.location.href = response.url;  

        }  

    })  

  

});

 代码如下 复制代码


//export.php

$data = $_POST['data'];

$xls = new PHPExcel();

$xls->loadData($formattedData);

$xls->exportToFile('excel.xls');

$response = array( 

'success' => true, 

'url' => $url 

); 


header('Content-type: application/json'); 

echo json_encode($response); 

?>

Other methods

The following is how PHPExcel generates multiple sheets:
The code is as follows Copy code
$sheet = $objPHPExcel->getActiveSheet(); $sheet->setCellValue('A1',$x); $sheet->setCellValue('B1',$y); For the second method, you can consider ajax to export in batches without refreshing the page every time.
The code is as follows Copy code
export to Excel $('#export').click(function() { $.ajax({ url: "export.php", data: getData(), //You can also get this place in php, generally read the database success: function(response){ window.location.href = response.url; } } }) });
The code is as follows Copy code
<🎜>//export.php <🎜> <🎜>$data = $_POST['data'];<🎜> <🎜>$xls = new PHPExcel(); <🎜> <🎜>$xls->loadData($formattedData); $xls->exportToFile('excel.xls'); $response = array( 'success' => true, 'url' => $url ); header('Content-type: application/json'); echo json_encode($response); ?> If the amount of data is large, it is recommended to use the second method, ajax, to export the data. The above method simply gives a process, you can add the details yourself!

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/630726.htmlTechArticleWe often use phpExcel to import or import xls files, but if the data exported at one time is relatively large, a memory overflow error will occur , let me summarize the solutions below. phpExcel will read the single...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Two Point Museum: All Exhibits And Where To Find Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Large memory optimization, what should I do if the computer upgrades to 16g/32g memory speed and there is no change? Large memory optimization, what should I do if the computer upgrades to 16g/32g memory speed and there is no change? Jun 18, 2024 pm 06:51 PM

For mechanical hard drives or SATA solid-state drives, you will feel the increase in software running speed. If it is an NVME hard drive, you may not feel it. 1. Import the registry into the desktop and create a new text document, copy and paste the following content, save it as 1.reg, then right-click to merge and restart the computer. WindowsRegistryEditorVersion5.00[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SessionManager\MemoryManagement]"DisablePagingExecutive"=d

Solution to Windows Update prompt Error 0x8024401c error Solution to Windows Update prompt Error 0x8024401c error Jun 08, 2024 pm 12:18 PM

Table of Contents Solution 1 Solution 21. Delete the temporary files of Windows update 2. Repair damaged system files 3. View and modify registry entries 4. Turn off the network card IPv6 5. Run the WindowsUpdateTroubleshooter tool to repair 6. Turn off the firewall and other related anti-virus software. 7. Close the WidowsUpdate service. Solution 3 Solution 4 "0x8024401c" error occurs during Windows update on Huawei computers Symptom Problem Cause Solution Still not solved? Recently, the web server needs to be updated due to system vulnerabilities. After logging in to the server, the update prompts error code 0x8024401c. Solution 1

The vitality of super intelligence awakens! But with the arrival of self-updating AI, mothers no longer have to worry about data bottlenecks The vitality of super intelligence awakens! But with the arrival of self-updating AI, mothers no longer have to worry about data bottlenecks Apr 29, 2024 pm 06:55 PM

I cry to death. The world is madly building big models. The data on the Internet is not enough. It is not enough at all. The training model looks like "The Hunger Games", and AI researchers around the world are worrying about how to feed these data voracious eaters. This problem is particularly prominent in multi-modal tasks. At a time when nothing could be done, a start-up team from the Department of Renmin University of China used its own new model to become the first in China to make "model-generated data feed itself" a reality. Moreover, it is a two-pronged approach on the understanding side and the generation side. Both sides can generate high-quality, multi-modal new data and provide data feedback to the model itself. What is a model? Awaker 1.0, a large multi-modal model that just appeared on the Zhongguancun Forum. Who is the team? Sophon engine. Founded by Gao Yizhao, a doctoral student at Renmin University’s Hillhouse School of Artificial Intelligence.

Slow Cellular Data Internet Speeds on iPhone: Fixes Slow Cellular Data Internet Speeds on iPhone: Fixes May 03, 2024 pm 09:01 PM

Facing lag, slow mobile data connection on iPhone? Typically, the strength of cellular internet on your phone depends on several factors such as region, cellular network type, roaming type, etc. There are some things you can do to get a faster, more reliable cellular Internet connection. Fix 1 – Force Restart iPhone Sometimes, force restarting your device just resets a lot of things, including the cellular connection. Step 1 – Just press the volume up key once and release. Next, press the Volume Down key and release it again. Step 2 – The next part of the process is to hold the button on the right side. Let the iPhone finish restarting. Enable cellular data and check network speed. Check again Fix 2 – Change data mode While 5G offers better network speeds, it works better when the signal is weaker

The U.S. Air Force showcases its first AI fighter jet with high profile! The minister personally conducted the test drive without interfering during the whole process, and 100,000 lines of code were tested for 21 times. The U.S. Air Force showcases its first AI fighter jet with high profile! The minister personally conducted the test drive without interfering during the whole process, and 100,000 lines of code were tested for 21 times. May 07, 2024 pm 05:00 PM

Recently, the military circle has been overwhelmed by the news: US military fighter jets can now complete fully automatic air combat using AI. Yes, just recently, the US military’s AI fighter jet was made public for the first time and the mystery was unveiled. The full name of this fighter is the Variable Stability Simulator Test Aircraft (VISTA). It was personally flown by the Secretary of the US Air Force to simulate a one-on-one air battle. On May 2, U.S. Air Force Secretary Frank Kendall took off in an X-62AVISTA at Edwards Air Force Base. Note that during the one-hour flight, all flight actions were completed autonomously by AI! Kendall said - "For the past few decades, we have been thinking about the unlimited potential of autonomous air-to-air combat, but it has always seemed out of reach." However now,

Lexar launches Ares Wings of War DDR5 7600 16GB x2 memory kit: Hynix A-die particles, 1,299 yuan Lexar launches Ares Wings of War DDR5 7600 16GB x2 memory kit: Hynix A-die particles, 1,299 yuan May 07, 2024 am 08:13 AM

According to news from this website on May 6, Lexar launched the Ares Wings of War series DDR57600CL36 overclocking memory. The 16GBx2 set will be available for pre-sale at 0:00 on May 7 with a deposit of 50 yuan, and the price is 1,299 yuan. Lexar Wings of War memory uses Hynix A-die memory chips, supports Intel XMP3.0, and provides the following two overclocking presets: 7600MT/s: CL36-46-46-961.4V8000MT/s: CL38-48-49 -1001.45V In terms of heat dissipation, this memory set is equipped with a 1.8mm thick all-aluminum heat dissipation vest and is equipped with PMIC's exclusive thermal conductive silicone grease pad. The memory uses 8 high-brightness LED beads and supports 13 RGB lighting modes.

Sources say Samsung Electronics and SK Hynix will commercialize stacked mobile memory after 2026 Sources say Samsung Electronics and SK Hynix will commercialize stacked mobile memory after 2026 Sep 03, 2024 pm 02:15 PM

According to news from this website on September 3, Korean media etnews reported yesterday (local time) that Samsung Electronics and SK Hynix’s “HBM-like” stacked structure mobile memory products will be commercialized after 2026. Sources said that the two Korean memory giants regard stacked mobile memory as an important source of future revenue and plan to expand "HBM-like memory" to smartphones, tablets and laptops to provide power for end-side AI. According to previous reports on this site, Samsung Electronics’ product is called LPWide I/O memory, and SK Hynix calls this technology VFO. The two companies have used roughly the same technical route, which is to combine fan-out packaging and vertical channels. Samsung Electronics’ LPWide I/O memory has a bit width of 512

Tesla robots work in factories, Musk: The degree of freedom of hands will reach 22 this year! Tesla robots work in factories, Musk: The degree of freedom of hands will reach 22 this year! May 06, 2024 pm 04:13 PM

The latest video of Tesla's robot Optimus is released, and it can already work in the factory. At normal speed, it sorts batteries (Tesla's 4680 batteries) like this: The official also released what it looks like at 20x speed - on a small "workstation", picking and picking and picking: This time it is released One of the highlights of the video is that Optimus completes this work in the factory, completely autonomously, without human intervention throughout the process. And from the perspective of Optimus, it can also pick up and place the crooked battery, focusing on automatic error correction: Regarding Optimus's hand, NVIDIA scientist Jim Fan gave a high evaluation: Optimus's hand is the world's five-fingered robot. One of the most dexterous. Its hands are not only tactile

See all articles