承上一篇

 

[Javascript] JS匯出html的table表格(續)-圖片匯出問題

 

前端js貌似無法直接將圖片匯出至excel,只能嘗試後端的方式。

 

這裡使用PhpSpreadsheet,一個很強大的php匯出表格檔案的plugin

https://github.com/PHPOffice/PhpSpreadsheet

文件

https://phpspreadsheet.readthedocs.io/en/latest/

--

以下是匯入圖片的code

 

$picUrl = "http://www.xxx.com/xxxxx.png";
            
$drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing();
//$drawing->setImageResource(imagecreatefrompng($picUrl));    // 讀取png檔
$drawing->setImageResource(imagecreatefromstring(file_get_contents($picUrl)));    // 泛用讀取圖片檔
$drawing->setCoordinates("M".$row);
$drawing->setWidthAndHeight(360270);
$drawing->setRenderingFunction(\PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing::RENDERING_JPEG);
$drawing->setMimeType(\PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing::MIMETYPE_DEFAULT);
$drawing->setWorksheet($sheet);

 

1. 建立drawing物件

2. setImageResource設定圖片來源

這邊本來是使用imagecreatefrompng,但是來源圖片似乎不是正統的png檔,會出現"imagecreatefrompng() is not a valid png file"的錯誤。

後來找到另外一種方式,使用imagecreatefromstring(file_get_contents($picUrl))的方式,解決圖片格式的問題。

3. setCoordinates設定該圖片的所屬儲存格

4. setWidthAndHeight設定圖片長寬

5. setRenderingFunction、setMimeType產生成圖片檔

6. setWorksheet將此drawing物件加入到sheet中

這樣就可以把圖片真正加入至excel中。

 

另外,必須設定該列列高,避免圖片超出該列的高度。

 

$sheet->getRowDimension($row)->setRowHeight(210'px');

 

--

參考 

https://stackoverflow.com/questions/5175473/i-cant-open-this-png-file-with-imagecreatefrompng

 https://stackoverflow.com/questions/54786609/phpspreadsheet-how-do-i-place-a-image-from-link-into-my-excel-file

 

 

arrow
arrow
    全站熱搜

    dizzy03 發表在 痞客邦 留言(0) 人氣()