« Programmation PHP/PHPExcel » : différence entre les versions

Contenu supprimé Contenu ajouté
DannyS712 (discussion | contributions)
m <source> -> <syntaxhighlight> (phab:T237267)
 
Ligne 10 :
Il faut la télécharger sur https://github.com/PHPOffice/PHPExcel :
{{terminal|clear=left|
<sourcesyntaxhighlight lang=bash>
composer require phpoffice/phpexcel
</syntaxhighlight>
</source>
|}}
 
Pour l'utiliser, l'inclure en début de fichiers :
<sourcesyntaxhighlight lang=php>
include 'PHPExcel/Classes/PHPExcel.php';
</syntaxhighlight>
</source>
On appellera ses instances "$objPHPExcel", qui représentent les classeurs.
 
== Création ==
Pour créer un fichier à partir de rien, soit <u>CreateXLS.php</u> un fichier situé à côté du répertoire de la bibliothèque nommé <u>PHPExcel</u>, brut de téléchargement (on appelle la feuille avec un nom très court car elle est souvent utilisée, "$s" pour "sheet") :
<sourcesyntaxhighlight lang=php>
$objPHPExcel = new PHPExcel;
$s = $objPHPExcel->getActiveSheet();
Ligne 36 :
header('Content-Disposition: attachment;filename="HelloWorld2.xlsx"');
$writer->save('php://output');
</syntaxhighlight>
</source>
 
== Ouverture ==
Pour ouvrir et lire un fichier existant :
<sourcesyntaxhighlight lang=php>
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$objPHPExcel = $objReader->load('./HelloWorld1.xlsx');
print $objPHPExcel->getActiveSheet()->getCell('A1')->getValue();
</syntaxhighlight>
</source>
 
== Conversion ==
Conversion d'un XLSX en CSV :
<sourcesyntaxhighlight lang=php>
$xlsx = PHPExcel_IOFactory::load('./HelloWorld1.xlsx');
$writer = PHPExcel_IOFactory::createWriter($xlsx, 'CSV');
Ligne 54 :
$writer->setEnclosure("");
$writer->save('./HelloWorld1.csv');
</syntaxhighlight>
</source>
 
Conversion d'un CSV en XLSX :
<sourcesyntaxhighlight lang=php>
$objReader = PHPExcel_IOFactory::createReader('CSV');
$objReader->setDelimiter(';');
Ligne 64 :
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('./HelloWorld3.xlsx');
</syntaxhighlight>
</source>
 
== Modifications ==
Les propriétés des cellules sont présentées sous forme de tableaux multidimensionnels :
<sourcesyntaxhighlight lang=php>
$style = array(
'borders' => array(
Ligne 104 :
$s->setCellValue('B1','9999999999999999999'); // Sans le format texte les nombres de plus de 15 chiffres sont arrondis
$writer->save('./HelloWorld4.xlsx');
</syntaxhighlight>
</source>
 
On peut aussi :
<sourcesyntaxhighlight lang=php>
// Récupérer la dernière ligne d'une feuille
$ligne = $s->getHighestRow();
// Insérer une ligne
$s->insertNewRowBefore($ligne + 1, 1);
</syntaxhighlight>
</source>
 
== Références ==