PHPExcel - error while trying to insert image after loading and writing

前端 未结 1 1091
梦毁少年i
梦毁少年i 2020-12-21 06:22

i saw this problem in so many posts. but none have been answered. first time when I insert image in an excel file, no problem is there.but if i load that excel file again a

相关标签:
1条回答
  • 2020-12-21 07:15

    I think this is a bug in PHPExcel in Classes\PHPExcel\Writer\Excel2007.php. Its easy to fix.

    Short answer is: comment out or remove lines 235-237. That would be this code:

            if (file_exists($pFilename)) {
                unlink($pFilename);
            }
    

    Your code will work then. I've checked, it works for me now.

    Now, some longer explanation. On lines 235-243 there is this code:

            if (file_exists($pFilename)) {
                unlink($pFilename);
            }
            // Try opening the ZIP file
            if ($objZip->open($pFilename, $zipOverWrite) !== true) {
                if ($objZip->open($pFilename, $zipCreate) !== true) {
                    throw new PHPExcel_Writer_Exception("Could not open " . $pFilename . " for writing.");
                }
            }
    

    Now, in this code, three things take place in order:

    1. If we're saving data to existing file, then this file is deleted (unlink)
    2. If we're saving data to existing file, overwrite this file
    3. If we're saving data to non-existing file, create it

    As you see, operation from step 2 is never executed because in step 1 file is always deleted. And in this process all previously existing file attachments are lost. That's why later you get error File XXX does not exist - indeed, your earlier image files are not present in newly created file.

    Obvious fix to this problem is to remove step 1. If file exists, it should be overwritten. I do not see any logical explanation for step 1. Maybe its a left over from some old code.

    0 讨论(0)
提交回复
热议问题