web-dev-qa-db-fra.com

PHPExcel: Téléchargez le fichier Excel côté client

Le problème a été résolu: pour les autres utilisateurs susceptibles de rencontrer ce problème, notez le codage du fichier PHP. Si vous utilisez PHPExcel, il doit s'agir d'un codage ANSII et non UTF8, sinon Excel sera téléchargé de manière corrompue. Les en-têtes ajoutés (réponse 1) ont résolu le problème après avoir modifié le codage du fichier lui-même.

J'utilise PHPExcel afin de créer un fichier Excel à partir d'une table de MYSQL DB afin que l'utilisateur puisse le télécharger sur son ordinateur.

Le code ci-dessous crée un fichier Excel correct mais le problème est qu'il est téléchargé sur mon serveur. J'ai lu dans le manuel PHPExcel que j'ai besoin d'ajouter des en-têtes:

header('Content-Type: application/vnd.ms-Excel');
header('Content-Disposition: attachment;filename="'.$name.'.xls"');
header('Cache-Control: max-age=0');
header('Cache-Control: max-age=1');
header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
header ('Pragma: public'); // HTTP/1.0

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');

Mais si je le fais, le fichier téléchargé est: 1. Il y a du jibrish à l'intérieur 2. Indique qu'Excel a besoin de le réparer car le fichier n'est pas bon ... Le problème est que ce fichier est enregistré au format UTF8 et que si je le code au format ANSI, il fonctionne correctement mais, bien entendu, il s'agit d'un changement manuel. un fonctionne correctement Excel pour atteindre les utilisateurs.

Quel est le bug?

Mon code qui fonctionne (mais téléchargez le fichier sur le serveur):

<?php
include 'connection.php';
include 'checkUser.php';

//Getting all the needed information from the DB
$task_id=$_GET['id'];
$query2 = "SELECT * FROM projects WHERE ProjectID=$task_id";
$data2 = mysqli_query($con, $query2);
$row = mysqli_fetch_array($data2);
$project_type = $row['ProjectType'];
$project_name = $row['ProjectName'];

switch ($project_type){
                    case 2: $NumberOfRows=22;  $project = "slivedetails"; break;
                    case 3: $NumberOfRows=30;  $project = "plivedetails"; break;
                    default: $NumberOfRows=0; $project = "none";
                    }
//column names
if ($project="slivedetails"){
    $ColumnNames = mysqli_query($con,"SHOW COLUMNS FROM slivedetails") or die("mysql error"); 
    }
else if ($project="plivedetails"){
    $ColumnNames = mysqli_query($con, "SHOW COLUMNS FROM plivedetails") or die("mysql error"); 
    }

$query = "SELECT * FROM $project WHERE TaskID=$task_id";
$data = mysqli_query($con, $query);
$num_rows = mysqli_num_rows($data); 


/** Include PHPExcel */
require_once 'PHPExcel_1.7.9_doc/Classes/PHPExcel.php';
require_once 'PHPExcel_1.7.9_doc/Classes/PHPExcel/IOFactory.php';


// create new PHPExcel object
$objPHPExcel = new PHPExcel();
    $objPHPExcel = new PHPExcel();

// writer already created the first sheet for us, let's get it
$objSheet = $objPHPExcel->getActiveSheet();
// rename the sheet
$objSheet->setTitle('Task Results');

// let's bold and size the header font and write the header
// as you can see, we can specify a range of cells, like here: cells from A1 to A4
$objSheet->getStyle('A1:AD1')->getFont()->setBold(true)->setSize(12);

$char = 65;
// write header]
for ($i=1;$i<=$NumberOfRows;$i++){
    $col_name = mysqli_fetch_array($ColumnNames);
    $objSheet->getCell(chr($char).'1')->setValue($col_name['Field']);
    $char++;
}

// Now we need to get the data from the DB. While we have a row in the result:
$rowIterator=2; //our row number. We begin from 2 because the first one is the title.

while ($RowInfo = mysqli_fetch_array($data)){
//We will fill the information based on the amount of columns:
$char = 65; //we set the first char as column A
for ($i=0;$i<$NumberOfRows;$i++){
    $objSheet->getCell(chr($char).$rowIterator)->setValue($RowInfo[$i]);
    $char++;
}
$rowIterator++;
}

// autosize the columns
$char = 65;
for ($i=1;$i<=$NumberOfRows;$i++){
    $objSheet->getColumnDimension(chr($char))->setAutoSize(true);
    $char++;
}

// create the writer
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, "Excel2007");
$objWriter->save('results.xlsx');


?>
10
Alex

Supprimer l'inclusion suivante:

require_once 'PHPExcel_1.7.9_doc/Classes/PHPExcel/IOFactory.php';

Vous avez déclaré l'objet deux fois. Supprimer l'un d'entre eux:

// create new PHPExcel object
$objPHPExcel = new PHPExcel();

Insérez les en-têtes suivants juste avant de créer le Writer:

header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
header("Content-Disposition: attachment; filename=\"results.xlsx\"");
header("Cache-Control: max-age=0");

Au lieu de ce qui suit (qui enregistre le fichier sur le serveur):

$objWriter->save('results.xlsx');

Insérez ce qui suit (qui créera le fichier téléchargeable):

$objWriter->save("php://output");

Cela devrait résoudre le texte charabia. Si vous recevez toujours ce texte, insérez le code suivant avant la dernière ligne ($objWriter->save("php://output");):

ob_clean();

Cela a fonctionné pour moi. J'espère que ça aide.

7
Placid

Cela devrait fonctionner, essayez de modifier votre code comme ceci:

header("Content-Type: application/vnd.ms-Excel");
header("Content-Disposition: attachment; filename=my_Excel_filename.xls");
header("Pragma: no-cache");
header("Expires: 0");

flush();

require_once 'PHPExcel.php';

$objPHPExcel = new PHPExcel();

// here fill data to your Excel sheet

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');

$objWriter->save('php://output');
2
Legionar