首页 > 解决方案 > 使用 PHPExcel 写入 excel 文件时超出内存

问题描述

我的 VPS 有 8GB 内存

当我尝试写 4000 行和 62 列时。1 列有图像(PHPExcel_Worksheet_MemoryDrawing)

在写入一些数据后,操作系统已经杀死了后台脚本,因为 VPS 没有更多的内存。

我正在使用 PHPExcel 1.7.8 版

我在每个循环中都写了 excel 文件。

图片写示例代码

$gdImage = imagecreatefromstring(file_get_contents($proof_photo_1));
if ($gdImage) {
    $objDrawing = new PHPExcel_Worksheet_MemoryDrawing();
    $objDrawing->setImageResource($gdImage);
    $objDrawing->setCoordinates("BA" . $i);
    $objDrawing->setWorksheet($objPHPExcel->getActiveSheet());
    $objDrawing->setHeight(150);
    $width = $objDrawing->getWidth() * 0.143;
    $height = $objDrawing->getHeight() * 0.75;
    if ($rowDim->getRowHeight() < $height) {
        $rowDim->setRowHeight($height);
    }
    $colDimSh = $objPHPExcel->getActiveSheet()->getColumnDimension("BA");
    $colDimSh->setAutoSize(false);
    $colDim = $objPHPExcel->getActiveSheet()->getColumnDimension("BA");
    if ($colDim->getWidth() < $width) {
        $colDim->setWidth($width);
    }
    unset($objDrawing);
} else {
    $objPHPExcel->getActiveSheet()->SetCellValue("BA" . $i, "-");
}

我尝试了很多方法来节省内存

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

在每个循环的旁边

if($i % 100 == 0){
    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
    $objWriter->save($csvPath);
    $objPHPExcel->disconnectWorksheets();
    unset($objWriter);
    unset($objPHPExcel);
    chmod($csvPath, 0777);

    $objPHPExcel = PHPExcel_IOFactory::load($csvPath);
    $objPHPExcel->setActiveSheetIndex(0);
}

以上需要花费大量时间来写入 excel 文件,有时文件会从开始重置。

标签: phpphpexcel

解决方案


推荐阅读