matsudada技術ブログ

日々の雑念と備忘録

PhpSpreadsheetで入力規則が読み込まれない

PhpSpreadsheetで入力規則が読み込まれない

半日近くはまったので記事にする。

環境

  • CentOS 7.5
  • PHP 7.2.10
  • Composer version 1.7.2
  • phpoffice/phpspreadsheet 1.6.0

現象

入力規則を設定していたExcelファイルを読み込んだ時に入力規則が読み込まれないので、
ファイルを保存すると設定していた入力規則が消える。

$reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
$spreadsheet = $reader->load("./template.xlsx");

$writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
$writer->save("./export.xlsx");

原因

入力規則が他のシートの値を参照する入力規則であり、バグによって消えていた。

入力規則:[=$I:$I]は消えない
入力規則:[=source!$A:$A]は消える

GitHubのissueを見つけ、まだリリースされていないことが判明した。

参考

Xls and Xlsx readers miss data validation for files saved with Excel #388 https://github.com/PHPOffice/PhpSpreadsheet/issues/388

Xml does not recognize data validations that references another sheet #639 https://github.com/PHPOffice/PhpSpreadsheet/issues/639

対応

入力規則を設定し、その後で保存することにした。

$reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
$spreadsheet = $reader->load("./template.xlsx");

# 入力規則を追加
$validation = $spreadsheet->getActiveSheet()->getCell('A1')->getDataValidation();
$validation->setType(\PhpOffice\PhpSpreadsheet\Cell\DataValidation::TYPE_LIST);
$validation->setErrorStyle(\PhpOffice\PhpSpreadsheet\Cell\DataValidation::STYLE_INFORMATION);
$validation->setAllowBlank(false);
$validation->setShowInputMessage(true);
$validation->setShowErrorMessage(true);
$validation->setShowDropDown(true);
$validation->setFormula1('source!$A:$A');


$writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
$writer->save("./export.xlsx");

参考

PhpSpreadsheet's documentation - Setting data validation on a cell - https://phpspreadsheet.readthedocs.io/en/latest/topics/recipes/#setting-data-validation-on-a-cell