Creare un file Excel con Zend Framework

Come esportare una tabella del database in Excel con lo Zend Framework.

Zend Framework di Gabriele Romanato

Esportare una tabella in Excel con Zend è un compito relativamente semplice. Quello che dobbiamo fare è impostare due metodi, uno nel Controller ed un altro nel Model designato. Il primo metodo fornirà la action effettiva dell'esportazione, mentre il secondo provvederà a reperire i dati dal database. Vediamo i dettagli di questa implementazione.

Quella che segue è la action definita nel Controller:


public function exportAction() 
{
        $this->_helper->layout()->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        
        $this->tbl = new Contacts();
        $xlsTbl = $this->tbl->exportContacts();
        
        header("Content-Type: application/vnd.ms-excel");
		header("Expires: 0");
		header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
		header("Content-Disposition: attachment;filename=contacts-download-" . time() . ".xls");
        
        echo "<table>$xlsTbl</table>";
}

Questo metodo imposta l'header HTTP per il file Excel e invoca il metodo corrispondente del Model. Notate come il Model, ossia Contacts, si limiti a reperire i dati dal database, come mostrato di seguito:


public function exportContacts() 
{

		$result = $this->_db->fetchAll('SELECT * FROM contacts');
		$xlsTbl = "<tr><th>First Name</th><th>Last Name</th><th>Email</th><th>Region</th><th>Enquiry Type</th><th>Telephone</th><th>Message</th><th>Type</th></tr>";
		foreach($result as $key=>$val){
			$xlsTbl .= "<tr>";
			$xlsTbl .= "<td>" . $val->first_name . "</td>";
			$xlsTbl .= "<td>" . $val->last_name . "</td>";
			$xlsTbl .= "<td>" . $val->email . "</td>";
			$xlsTbl .= "<td>" . $val->region . "</td>";
			$xlsTbl .= "<td>" . $val->enquiry_type . "</td>";
			$xlsTbl .= "<td>" . $val->telephone . "</td>";
			$xlsTbl .= "<td>" . $val->message . "</td>";
			$xlsTbl .= "<td>" . $val->type . "</td>";
			$xlsTbl .= "</tr>";
		}
			
		return $xlsTbl;
}

Ovviamente potete perfezionare l'esportazione aggiungendo campi extra al file di Excel generato. Tenete comunque presente che Excel è sensibile al tipo di dati contenuto nelle singole celle.