使用PHPSpreadsheet打开受密码保护的XLSX文件

时间:2018-04-20 12:31:31

标签: php phpspreadsheet phpoffice

我尝试打开受PHPSpreadsheetdocumentation)密码保护的Excel文件(.xlsx)。我知道密码,但我找不到打开它的方法。

load()的{​​{1}}方法无法插入密码,当我尝试加载文件时,它会返回错误(当然)。

\PhpOffice\PhpSpreadsheet\Reader\Xlsx

这是错误

  

警告:ZipArchive :: getFromName():第311行的/PHPOffice/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx.php中的无效或未初始化的Zip对象       警告:ZipArchive :: getFromName():313行/PHPffice/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx.php中的无效或未初始化的Zip对象       警告:在第350行的/PHPOffice/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx.php中为foreach()提供的参数无效       警告:ZipArchive :: getFromName():第311行的/PHPOffice/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx.php中的无效或未初始化的Zip对象       警告:ZipArchive :: getFromName():313行/PHPffice/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx.php中的无效或未初始化的Zip对象       警告:在第397行的/PHPOffice/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx.php中为foreach()提供的参数无效       警告:ZipArchive :: getFromName():第311行的/PHPOffice/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx.php中的无效或未初始化的Zip对象       警告:ZipArchive :: getFromName():313行/PHPffice/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx.php中的无效或未初始化的Zip对象       警告:在1855行的/PHPOffice/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx.php中为foreach()提供的参数无效       警告:ZipArchive :: close():1883行/PHPffice/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx.php中的无效或未初始化的Zip对象

此代码如何处理密码?

2 个答案:

答案 0 :(得分:1)

欢迎您查看我的 PHPDecryptXLSXWithPassword 存储库。

它也适用于 DOCX/PPTX 文件,但此答案特定于您的问题:首先使用密码解密文件,然后使用 PHPSpreadsheet 使用解密后的文件。

这是一个例子:

require_once('PHPDecryptXLSXWithPassword.php');

$encryptedFilePath = 'hello world.xlsx';
$password = 'mypassword'; // password to "open" the file
$decryptedFilePath = 'temp_path_to_decrypted_file.xlsx';

decrypt($encryptedFilePath, $password, $decryptedFilePath);

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

$reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
$spreadsheet = $reader->load($decryptedFilePath);
$sheet = $spreadsheet->getActiveSheet();
echo $sheet->getCell('A1')->getValue() . "\n";

注意:这是一个实验性代码,因此请谨慎使用。请勿在生产中使用!

答案 1 :(得分:0)

此刻我无法尝试,但我想你必须做这样的事情:

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

$reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
$spreadsheet = $reader->load('hello world.xlsx');
$sheet = $spreadsheet->getActiveSheet();
$sheet->getProtection()->setSheet(true);
$sheet->getProtection()->setPassword('THEPASSWORD');
echo $sheet->getCell('A1')->getValue() . "\n";

我不确定,明天我会到办公室去试试。