Skip to content
Advertisement

Open a password protected EXCEL in wamp using PHP

I have an excel that has a password (When you open it, it asks for a password). I want to open it and save it to a new folder. Supposing that there is no password my script would be :

    <?php

    $url = 'http://localhost/1472742721137_Book1.xlsx';
    $destination_folder = $_SERVER['DOCUMENT_ROOT'].'/YOLO/';


        $newfname = $destination_folder .'Book1.xlsx'; //set your file ext

        $file = fopen ($url, "rb");

        if ($file) {
          $newf = fopen ($newfname, "a"); // to overwrite existing file

          if ($newf)
          while(!feof($file)) {
            fwrite($newf, fread($file, 1024 * 8 ), 1024 * 8 );

          }
        }

        if ($file) {
          fclose($file);
        }

        if ($newf) {
          fclose($newf);
        }

    ?>

How can I mention the password of the file in the fopen function? It must be only one line that does that.

Otherwise, I will have to use PHPExcel but that is something I want to avoid as it brings me many errors even though I am trying to make it work for a NON protected excel file.

My steps :

a) I downloaded the files and extracted them from github .

b) I then added this script:

<?php

include '/Classes/PHPExcel.php';

$url = '1472742721137_Book1.xlsx';
$destination_folder = $_SERVER['DOCUMENT_ROOT'].'/YOLO/';

$reader = PHPExcel_IOFactory::createReaderForFile($url);
$reader->setReadDataOnly(true);
$workbook = $reader->load($url);
$objWriter->save($destination_folder);

?>

c) I am getting this errors :

enter image description here

UPD:

I made the script work finally. Now, all I need is to add the line that will get the password. The file has a password that I need to add in my script in order to open it and then save it (without a password).

enter image description here

My script :

<?php

include '/Classes/PHPExcel.php';

$url = 'AAAAA.xlsx';
$destination_folder = $_SERVER['DOCUMENT_ROOT'].'/YOLO/';

$fileType=PHPExcel_IOFactory::identify($url);
$objReader = PHPExcel_IOFactory::createReader($fileType);

$objReader->setReadDataOnly(true);   
$objPHPExcel = $objReader->load($url);

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, $fileType);
$objWriter->save($destination_folder.'/output.xlsx');

?>

Advertisement

Answer

If you are working only on Excel files, I recommend using the PHPExcel module, available here You can open password protected sheets since the 1.8.0 release I think

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement