问题描述
我使用PHPSpreadsheet编辑现有的Excel文件并在其中添加一些图像。但是有时它会失去Excel中现有图表的样式。重置背景色或图表的比例。一些图表保持不变。
有人可以说为什么PHPSpreadsheet重置现有图表的样式/比例以及如何抑制这种副作用吗?
<?PHP
include 'vendor/autoload.PHP';
use PHPOffice\PHPSpreadsheet\IOFactory;
use PHPOffice\PHPSpreadsheet\Worksheet\Drawing;
use PHPOffice\PHPSpreadsheet\Writer\Xlsx;
$inputExcelPath = __DIR__.'/assets/badExcel/an_excel_file.xlsx';
$outputExcelFile = __DIR__.'/excelOutput/'.time().'_'.'/an_excel_file.xlsx';
//load excel
$excelFIleInfo = new SplFileInfo($inputExcelPath);
$excelReader = IOFactory::createReaderForFile($excelFIleInfo->getRealPath());
$excelReader->setIncludeCharts(true);
$excel = $excelReader->load($excelFIleInfo->getRealPath());
//end loading
$excel->setActiveSheetIndex((int)0);
//add image
$drawing = new Drawing();
$drawing->setPath(__DIR__.'/assets/image.jpg');
$drawing->setCoordinates('Q5');
$drawing->setHeight(80);
$drawing->setWidth(140);
$drawing->setWorksheet($excel->getActiveSheet());
//end add image
//save edited excel to a new file
$writer = new Xlsx($excel);
$writer->setPreCalculateFormulas(false);
$writer->setIncludeCharts(true);
$writer->save($outputExcelFile);
Link to an example of the excel file
解决方法
Php电子表格将其已知格式填充在副本/模板中。所有未知的Fromatting都将在文件保存时删除。