Ver Mensaje Individual
  #5 (permalink)  
Antiguo 06/03/2013, 08:10
Avatar de evolutionrgm
evolutionrgm
 
Fecha de Ingreso: mayo-2011
Mensajes: 108
Antigüedad: 12 años, 11 meses
Puntos: 5
Respuesta: Exportar de mysql a excel

estimado junto con saludar le citare un ejemplo que un usuario compartio con nosotros .. yo lo utilizo en mis aplicaciones y funciona de maravillas

Código PHP:
Ver original
  1. /*
  2. Mysql To Excel
  3. Generación de excel versión 1.0
  4. Nicolás Pardo - 2007
  5. */
  6. #Conexion a la db
  7. require_once('__conn.php');
  8.  
  9. #Sql, acá pone tu consulta a la tabla que necesites exportar filtrando los datos que creas necesarios.
  10. $sql = "
  11. SELECT
  12.    *
  13. FROM
  14.    usuarios
  15. WHERE
  16.    activo > -1
  17. ORDER BY
  18.    codigo DESC
  19. ";
  20.  
  21. $r = mysql_query( $sql ) or trigger_error( mysql_error($conn), E_USER_ERROR );
  22. $return = '';
  23. if( mysql_num_rows($r)>0){
  24.     $return .= '<table border=1>';
  25.     $cols = 0;
  26.     while($rs = mysql_fetch_row($r)){
  27.         $return .= '<tr>';
  28.         if($cols==0){
  29.             $cols = sizeof($rs);
  30.             $cols_names = array();
  31.             for($i=0; $i<$cols; $i++){
  32.                 $col_name = mysql_field_name($r,$i);
  33.                 $return .= '<th>'.htmlspecialchars($col_name).'</th>';
  34.                 $cols_names[$i] = $col_name;
  35.             }
  36.             $return .= '</tr><tr>';
  37.         }
  38.         for($i=0; $i<$cols; $i++){
  39.             #En esta iteración podes manejar de manera personalizada datos, por ejemplo:
  40.            if($cols_names[$i] == 'fechaAlta'){ #Fromateo el registro en formato Timestamp
  41.                $return .= '<td>'.htmlspecialchars(date('d/m/Y H:i:s',$rs[$i])).'</td>';
  42.             }else if($cols_names[$i] == 'activo'){ #Estado lógico del registro, en vez de 1 o 0 le muestro Si o No.
  43.                $return .= '<td>'.htmlspecialchars( $rs[$i]==1? 'SI':'NO' ).'</td>';
  44.             }else{
  45.                 $return .= '<td>'.htmlspecialchars($rs[$i]).'</td>';
  46.             }
  47.         }
  48.         $return .= '</tr>';
  49.     }
  50.     $return .= '</table>';
  51. }
  52. #Cambiando el content-type más las <table> se pueden exportar formatos como csv
  53. header("Content-type: application/vnd-ms-excel; charset=iso-8859-1");
  54. header("Content-Disposition: attachment; filename=NombreDelExcel_".date('d-m-Y').".xls");
  55. echo $return;