首先确保安装了phpSpreadsheet以及mpdf插件
composer require phpoffice/phpspreadsheet
composer require mpdf/mpdf
代码示例如下:
public function excelConvertPdf($file,$path)
{
$reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReaderForFile($file);
$phpWord = $reader->load($file);
$phpWord ->getDefaultStyle()->applyFromArray(
[
// 字体
'font'=>[
'name' => 'Arial',
'bold' => true,
'italic' => false,
'underline' => \PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_DOUBLE,
'strikethrough' => false,
'color' => [
'rgb' => '808080'
]
],
// 边框
'borders' => [
'allBorders' => [
'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
]
],
'alignment' => [
'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
'wrapText' => true,
],
'quotePrefix' => true
]
);
$xmlWriter = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($phpWord,'Mpdf');
$xmlWriter->writeAllSheets();
$name = '123.pdf';
$xmlWriter->save($path.'\\'.$name);
}
此时遇到中文可能会出现乱码的情况,解决办法即是修改phpspreadsheet 中 Mpdf类文件,代码片段如下:
值得注意的是,转换后pdf的边框如果显示不全,此时需要检查excel文件的单元格问题