aktuelle.kurse/old_m133/Modul_Unterlagen_133_VOR/08-Uebungen/03 PHP Grundlagen/PHP_Excel/export_to_excel.php

70 lines
2.3 KiB
PHP
Raw Normal View History

2022-02-23 22:44:33 +01:00
<?
function exportToExcel($tableName, $columnNames, $attributes) {
//Sind alle Parameter gesetzt?
if(isset($tableName) && isset($columnNames) && isset($attributes)){
//Verbindung zu Excel herstellen
$excel = new COM("Excel.application") or Die ("Could not connect to Excel.Application");
//Pfad zum Excel-File das ge<67>ffnet werden soll.
$workbook="Y:\\xchange/grp2/migrations-applikation/excel import,export/vba-export.xls";
//<2F>ffnen des Files im Excel
$workbook = $excel->Workbooks->Open($workbook);
//Setze das Application-Window auf true, Excel wird sichtbar
$excel->Application->Visible = 1;
//Dieser try wird gebraucht um die Exception bei $excel->Sheets($tableName)
//abzufangen, die auftritt wenn es noch kein Sheet mit dem Namen gibt.
//anmerkung: sch<63>nere Variante w<>re eine Methode die abcheckt ob ein Sheet existiert
try{
$sheet = $excel->Sheets($tableName);
echo "Sheet existiert bereits. Das Sheet >>".$sheet->Name."<< wird gel<65>scht...<br>";
$sheet->Delete();
echo "<br>Sheet wurde gel<65>scht.";
} catch (com_exception $exception){
//do nothing
//f<>ngt die Exception-Ausgabe ab. Hier weiss ich dass kein Sheet mit
//dem Namen gefunden wurde, somit muss auch nichts gel<65>scht werden.
}
//Ein leeres Sheet wird angeh<65>ngt
$sheet = $excel->Worksheets->Add();
//Das sheet wird umbenannt in den Tabellenname
$sheet->Name = $tableName;
//Einf<6E>gen der Attribute
for ($i = 0; $i < count($attributes); $i++)
{
for ($index = 0; $index < count($attributes[$i]); $index++)
{
//Zugriff auf Cell, cell wird zwischengespeichert
$cell = $sheet->Cells($index+1,$i+1);
//Neuer Inhalt wird gesetzt
$cell->value = $attributes[$i][$index];
}
}
echo "<br><br>Daten erfolgreich ins Excel exportiert!";
//Workbook wird gespeichert
$ret = $workbook->save();
//Wenn erfolgreich gespeichert ...
if($ret == 1){
// ... schliessen des Workbooks und des Excels.
$workbook->close();
$excel->Quit();
unset($workbook);
unset($excel);
} else {
echo "ERROR: Schliessen des Dokumentes fehlgeschlagen. Dokument konnte nicht gespeichert werden.";
}
} else {
echo "ERROR: Nicht alle Variabeln <20>bergeben!";
}
}
exportToExcel("test", array("a", "b", "c"), array("a1", "b2", "c3"));
?>