我已经成功使用composer安装了PhpSpreadsheet和dompdf。 我的要求是我需要将Excel工作表转换为pdf,使用默认设置即可正常工作,这是我使用的代码。
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Writer\Csv;
use PhpOffice\PhpSpreadsheet\Exception;
use PhpOffice\PhpSpreadsheet\IOFactory;
use \PhpOffice\PhpSpreadsheet\Writer\Pdf\Dompdf;
$spreadsheet = new Spreadsheet();
try {
$sheet = $spreadsheet->getActiveSheet();
// code to fill in the data
$spreadsheet->getActiveSheet()->fromArray(
$data, // The data to set
NULL, // Array values with this value will not be set
'A2' // Top left coordinate of the worksheet range where
);
} catch (Exception $e) {
}
$writer = new Xlsx($spreadsheet);
try {
IOFactory::registerWriter("PDF", Dompdf::class);
$pdfwriter = IOFactory::createWriter($spreadsheet, 'PDF');
$pdfwriter->save($filepath . 'pdf_test.pdf');
} catch (\PhpOffice\PhpSpreadsheet\Writer\Exception $e) {
}
为了简洁起见,我跳过了代码,此代码可以正常工作并生成pdf文件,我要求pdf必须以横向模式打印,为此,文档中提到了Custom implementation or configuration of the pdf library
,因此我创建了一个名为看起来像这样的PDFBase_DOMPDF
use Dompdf\Dompdf;
class PDFBase_DOMPDF extends Dompdf
{
}
我已经创建了一个名为PDFBase_Writer
的文件,如下所示。
use PhpOffice\PhpSpreadsheet\Writer\Pdf\Dompdf;
class PDFBase_Writer extends Dompdf
{
protected function createExternalWriterInstance()
{
$instance = new PDFBase_DOMPDF();
$instance->setPaper('A4', 'landscape');
return $instance;
}
}
我修改了原始代码以使用新的pdf类,因此将行更改为此。
IOFactory::registerWriter("PDF", PDFBase_Writer::class);
问题是我收到以下错误的异常
Registered writers must implement PhpOffice\PhpSpreadsheet\Writer\IWriter
我该如何解决?
答案 0 :(得分:0)
使用基本的PhpSpreadsheet类无法读写持久性存储。为此,PhpSpreadsheet提供了读取器和编写器,它们是\ PhpOffice \ PhpSpreadsheet \ Reader \ IReader和\ PhpOffice \ PhpSpreadsheet \ Writer \ IWriter的实现。
您必须像这样加载Excel文件:
$reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
$reader->setReadDataOnly(true);
$spreadsheet = $reader->load("TestRead.xlsx");
答案 1 :(得分:0)
Registered writers must implement PhpOffice\PhpSpreadsheet\Writer\IWriter
PHPSpreadsheet Writer类必须实现IWriter
接口中定义的所有方法。您正在创建一个新的Writer,因此它需要提供所有这些方法的实现:
interface IWriter
{
/**
* IWriter constructor.
*
* @param Spreadsheet $spreadsheet
*/
public function __construct(Spreadsheet $spreadsheet);
/**
* Save PhpSpreadsheet to file.
*
* @param string $pFilename Name of the file to save
*
* @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
*/
public function save($pFilename);
}
因此,您的Writer需要实现一个接受Spreadsheet
对象作为参数的构造函数,以及一个接受文件名(作为字符串)参数的save()
方法。