How to download Excel file from the WEB server?

0

I have an Excel 2007 file (xlsx extension) in a server directory (external to the web root), the question is: How can I download it from a web link?

  

For more clarity the file is e: \ clients \ company \ prueba.xlsx

     

I have a website on link

     

I need to download that xlsx test file via a link in    link

I've tried with this code PHP

$archivo = "e:\clientes\empresa\prueba.xlsx";

header('Content-Disposition: attachment; filename=' . $archivo);

header("Content-Type: application/vnd.openxmlformats-   officedocument.spreadsheetml.sheet");

header('Cache-Control: must-revalidate, post-check=0, pre-check=0');

header('Content-Length: '.filesize($archivo));

readfile($archivo);

The file goes down but when you open it with Excel 2007 it does not recognize it as a valid file.

Thanks for your help

    
asked by jtraslavi 18.04.2017 в 21:04
source

3 answers

1

Try this, this code has already been used for a while and to work properly requires the PHPExcel library.

header("Content-Type: application/vnd.ms-excel");
$nombre = "NombreArchivo";  
    header("Content-Disposition: attachment; filename=\"$nombre.xlsx\"");
    header("Cache-Control: max-age=0");
    $writer = PHPExcel_IOFactory::createWriter($excel, "Excel2007");
    $writer->setIncludeCharts(true);
    $writer->setPreCalculateFormulas(true);
    $writer->save("php://output");
    exit;
    
answered by 15.01.2018 в 17:09
0

Try using a different variable for the name and another to refer to the location of the file.

$archivo = "e:\clientes\empresa\prueba.xlsx";
$nombre = "prueba.xlsx";

header('Content-Disposition: attachment; filename=' . $nombre );

header("Content-Type: application/vnd.openxmlformats-   officedocument.spreadsheetml.sheet");

header('Cache-Control: must-revalidate, post-check=0, pre-check=0');

header('Content-Length: '.filesize($archivo));

readfile($archivo);
    
answered by 18.04.2017 в 21:12
0

Try this way:

<?php
// Asegurate de que es un archivo realmente válido
// Recuperamos el archivo
$archivo = "e:\clientes\empresa\prueba.xlsx";

// Nos aseguramos que el archivo exista
if (!file_exists($archivo)) {
    echo "El fichero $archivo no existe";
    exit;
}

// Establecemos el nombre del archivo
header('Content-Disposition: attachment;filename="'. 'Excel_'.date('dmYHis').'.xlsx"');

// Esto  
// header("Content-Type: application/vnd.openxmlformats-   officedocument.spreadsheetml.sheet");
// lo cambiamos por esto
header('Content-Type: application/vnd.ms-excel');

// Indicamos el tamaño del archivo 
header('Content-Length: '.filesize($archivo));

// Evitamos que sea cachedo 
header('Cache-Control: max-age=0');

// Realizamos la salida del fichero
readfile($archivo);

// Fin del cuento
exit;
?>
    
answered by 18.04.2017 в 22:19