Foros del Web » Programando para Internet » PHP »

PHP con EXCEL

Estas en el tema de PHP con EXCEL en el foro de PHP en Foros del Web. Que tal amigos, me gstaria pasar los datos de mi aplicativo web a una hoja de excel, en mi aplicativo hago una consulta a mi ...
  #1 (permalink)  
Antiguo 03/03/2005, 12:35
 
Fecha de Ingreso: agosto-2004
Mensajes: 258
Antigüedad: 19 años, 7 meses
Puntos: 0
Pregunta PHP con EXCEL

Que tal amigos, me gstaria pasar los datos de mi aplicativo web a una hoja de excel, en mi aplicativo hago una consulta a mi base de datos la cual me retorna varios registros, me gustaria que esos datos se guarden en excel. me podrian ayudar con algun manual y ejemplos de como hacer esto, encontre una clase pero no le entiendo mucho.. espero me puedan ayudar... gracias por su tiempo
  #2 (permalink)  
Antiguo 03/03/2005, 12:45
O_O
 
Fecha de Ingreso: enero-2002
Ubicación: Santiago - Chile
Mensajes: 34.417
Antigüedad: 22 años, 2 meses
Puntos: 129
Si dices que encontrastes una "classe" para tal fin .. lo mejor sería que indiques aquí cual es y comentes los problemas que tengas para llegar a usarla ...

Por lo demás .. en las FAQ's de este foro tienes un ejemplo de como generar una hoja de cálculo (planilla) Excel .. en principio este reconoce una estructura de datos en forma de tabla HTML como una planilla Excel básica ..

Un saludo,
  #3 (permalink)  
Antiguo 03/03/2005, 12:52
 
Fecha de Ingreso: agosto-2004
Mensajes: 258
Antigüedad: 19 años, 7 meses
Puntos: 0
De acuerdo

esta es la clase, hum voy a revisar la FAQ, gracias

Código PHP:
Clase para crear y modificar un archivo Excel desde PHP

2002-03-22
1876 lecturas 

Esta clase de PHP permite crear, cargar, leer, escribir y grabar en libros y hojas de Microsoft Excel. 
 

<?php 
/* Class for use with PHP4 scripts only*/ 
/* 
* This is an Excel class to create,load,read,write,save and use some of the internal 
* functionalities of workbooks and sheets. 
* Tested with Windows 98 - MS Office 2000 
* Apache 1.3.9 PHP4.02 Running as CGI 
* (c) Alain M. Samoun 09/2000. 
[email protected] 
* Gnu GPL code (see www.fsf.org for more information). 
*/ 

class Excel 
/* variables */ 
var $ex
var 
$pathin
var 
$pathout
var 
$workbook
var 
$sheet
var 
$visible
var 
$fformatin
var 
$fformatout
var 
$cell
var 
$rangesens
var 
$range
var 
$ext
var 
$oext
var 
$error 0
var 
$msg_error

/* Constructor */ 
function excel() 

#Instantiate Excel 
$this->ex = new COM("Excel.Application") or $this->error 1
if (
$this->get_error()==0
return 
true
else 
return 
false


function 
XL($workbook,$pathin="",$sheet="Hoja1"

if (
$workbook != ""

#Load the workbook 
$wkb = @$this->ex->application->Workbooks->Open($pathin.$workbook) or $this->error 2
}else{ 
#New workbook 
$wkb = @$this->ex->application->Workbooks->Add or $this->error 3

if (
$this->error==0
if (
$sheet != ""

#Activate the sheet 
$sheets = @$wkb->Worksheets($sheet) or $this->error 4
}else{ 
#new sheet 
$sheet "Hoja1" 

#Excel Won't prompt the user when replacing or closing workbooks 
#Comment the line below if you want Excel to prompt 
// $this->ex->application->DisplayAlerts = "False"; 
if ($this->get_error()==0
return 
true
else 
return 
false


function 
readrange($sheet="Hoja1",$range

#Read all the cells in the range to $result and return it 
unset ($result); 
$range trim($range); 
#Determine start and end of range 
$tokstart strtok($range,":"); 
$tokend strtok(":"); 
if (
$tokend ==""

#Read one single cell 
$sheets $this->ex->Application->Worksheets($sheet); 
$sheets->activate
#Select the cell 
$selcell $sheets->Range($range); 
$selcell->activate
return 
$selcell->value

#Read a range of cells 
#determine column and row numbers 
$sheets $this->ex->Application->Worksheets($sheet); 
$sheets->activate
$rgstart $sheets->range($tokstart); 
$colstart $rgstart->column
$rowstart $rgstart->row
$rgend $sheets->range($tokend); 
$colend $rgend->column
$rowend $rgend->row
if (
$colstart>$colend or $rowstart>$rowend

Print (
"Notation Error! Cell Column/Row should be increasing."); 
return; 

#Now read each cell 
if ($colstart == $colend

#Read Vertically 
$j=0
For (
$i$rowstart$i<=$rowend$i++) 

$selcell $sheets->cells($i,$colstart); 
$selcell->activate
$result[$j] = $selcell->value
$j++; 

}else 

#Read horizontally 
$j=0
For (
$i$colstart$i<=$colend$i++) 

$selcell $sheets->cells($rowstart,$i); 
$selcell->activate
$result[$j] = $selcell->value
$j++; 


return 
$result

 
function 
writerange($sheet="Hoja1",$range,$value

#Fill up all the cells in the range with array 
$range trim($range); 
#Determine start and end of range 
$tokstart strtok($range,":"); 
$tokend strtok(":"); 
if (
$tokend ==""

# Write to a single cell in the active sheet 
$cell trim($range); 
#Select the sheet 
$sheets $this->ex->Application->Worksheets($sheet); 
$sheets->activate
#Select the cell 
$selcell $sheets->Range($cell); 
$selcell->activate
$selcell->value $value
return; 

#determine column and row numbers 
$sheets $this->ex->Application->Worksheets($sheet); 
$sheets->activate
$rgstart $sheets->range($tokstart); 
$colstart $rgstart->column
$rowstart $rgstart->row
$rgend $sheets->range($tokend); 
$colend $rgend->column
$rowend $rgend->row
if (
$colstart>$colend or $rowstart>$rowend

Print (
"Notation Error! Cell Column/Row should be increasing."); 
return; 

#Now write each cell 
if ($colstart == $colend

#write Vertically 
$j=0
For (
$i$rowstart$i<=$rowend$i++) 

$selcell $sheets->cells($i,$colstart); 
$selcell->activate
$selcell->value $value[$j]; 
$j++; 

}else 

#Write horizontally 
$j=0
For (
$i$colstart$i<=$colend$i++) 

$selcell $sheets->cells($rowstart,$i); 
$selcell->activate
$selcell->value $value[$j]; 
$j++; 


return 
1

function 
saveas($workbook,$pathout,$ext


#First get the file format code for the extension $ext 
$code $this->fileformater($ext); 
$basefile strtok($workbook,"."); 
$newworkbook $basefile."."."$ext"

#If no prompt and file exists it will be replaced. 

#Save the current workbook as new workbook 
#The following line will work for converting spreadsheets file to xls 
#but if the original is an excel file and the new file another format 
#then it may not work because limitations of excel.(See excel doc) 
$this->ex->Application->ActiveWorkbook->SaveAS($pathout.$newworkbook,$code); 

return 
1

 
function 
fileformater($ext

switch(
strtolower($ext)) 

case 
"slk"
return 
2
break; 
case 
"xlt"
return -
4143
break; 
case 
"txt"
return -
4158
break; 
case 
"csv"
return 
6
break; 
case 
"xlw"
return 
35
break; 
case 
"w4k"
return 
38
break; 
case 
"wq1"
return 
34
break; 
case 
"prn"
return -
4158
break; 
case 
"dif"
return 
9
break; 
case 
"xla"
return -
4143
break; 
case 
"wk3"
return 
32
break; 
case 
"xls"
return -
4143
break; 
case 
"htm"
return 
44
break; 
case 
"wks"
return 
4
break; 
default: 
return -
4143



function 
XLTranslate($pathin,$pathout,$oext,$ext,$kill=0

#This function will translate automatically all spreadsheets files, with the 
#$oext extension, in the $pathin directory, to another spreadsheet file, 
#with the $ext extension, to the $pathout directory. 
#It will erase the original file if $kill switch = 1. 
#Limitations: Will work always when translating none excel files to 
#excel files(Extension=xl*) and with the translation xls->htm . It will 
#not generally work when translating excel files to other formats because 
#the questions asked by the excel program stop the script. 
#Get all files in the source directory $pathin to the $filelist array 
chdir($pathin); 
$dir=dir ("."); 
$i=1
while(
$file=$dir->read()) 

$filelist [$i] = $file
$i++; 

$dir->close
#Translate each file, with the original extension $oext, in the $filelist 
#to the needed extension $ext. 
for ($i=1;$i<= sizeof($filelist); $i++) 

$file $filelist[$i]; 
$basefile strtok($file,"."); 
$extension strtok("."); 

if (
strtolower($extension) == strtolower($oext)) 

echo 
"<BR> $file"
$this->XL($file,$pathin,$sheet=""); 
$this->saveas($file,$pathout,$ext,""); 
#Erase the original file if $kill=1 
if ($kill

chmod ($file,0777); 
unlink ($pathin.$file); 

#Close the new workbook 
$this->closeXL(); 


return 
1

 
function 
closexl() 

#Close active workbook without prompt from Excel 
$this->ex->application->ActiveWorkbook->Close("False"); 
return 
1

function 
runfunction($funct,$arrayparam

#Run and return value of an excel function 
$params implode(",",$arrayparam); 
eval (
"$result = $this->ex->application->$funct($params);"); 
return 
$result

Function 
runmacro($workbook,$macroname

$this->ex->application->Run("$workbook!$macroname"); 
return 
1

Function 
createhyperlink($sheet="Hoja1",$cell,$hyperl

#Not working as 9/2/00 4:57PM 
print "<br>link = $hyperl <br>"
$sheets $this->ex->Application->Worksheets($sheet); 
$sheets->activate
#Select the cell 
$selcell $sheets->Range($cell); 
$sheets->hyperlinks->add($selcell,$hyperl); 

return 
1

function 
calculate($sheet="Hoja1"

#Calculate (update) the current sheet 
$sheets $this->ex->Application->Worksheets($sheet); #Select the sheet 
$sheets->activate
$sheets->Calculate
return 
1


function 
get_error() 

return 
$this->error


function 
set_error($id_error

$this->error $id_error


function 
get_msg_error($id_error

switch(
$id_error

// case 1: return "Did not instantiate Excel"; 
case 1: return "No se puede abrir el fichero Excel"
// case 2: return "Did not open $pathin $workbook"; 
case 2: return "No se puede abrir el fichero Excel seleccionado"
// case 3: return "Unable to add a workbook"; 
case 3: return "Unable to add a workbook"
// case 4: return "Unable to activate $sheet"; 
case 4: return "No se puede abrir el fichero Excel seleccionado"


/* end of Excel class */ 
?>
  #4 (permalink)  
Antiguo 03/03/2005, 13:06
O_O
 
Fecha de Ingreso: enero-2002
Ubicación: Santiago - Chile
Mensajes: 34.417
Antigüedad: 22 años, 2 meses
Puntos: 129
Bueno .. pero esa classe no tiene un ejemplo .. o manual de uso? ... ALgunos métodos se pueden "deducir" que hacen o los parámetros de estos .. pero sería recomendable un ejemplo de uso o documentación más extensa para no estar "probando" a ver que pasa ..

Por lo demás .. tiene muy buena pinta esa classe, genera un ".xls" "nativo" de Excel .. (o se puede hacer) .. No es tan simple como los ejemplos que te mencioné que veras en las FAQ's.


Un saludo,
  #5 (permalink)  
Antiguo 04/03/2005, 10:26
 
Fecha de Ingreso: agosto-2004
Mensajes: 258
Antigüedad: 19 años, 7 meses
Puntos: 0
De acuerdo

exacto, el mismo te crea el archivo de excel y mira si tu me dices que es algo dificl imaginate yo que ahun soy novato en esto, si he visto los ejemplos de la FAQ, es solo generar tu tabla y guaradarlo con extension xls, voy a probar a ver que me resulta, pero me llamo mucha la atencion esta clase, el problema es que no encontre ningun manual de uso ni nada. ni ejemplos es por eso que no se como utilizarla. espero me puedas ayudar a entender esta clase, ya que me ha dado mucha curiosidad... gracias por tu ayuda
  #6 (permalink)  
Antiguo 04/03/2005, 10:58
O_O
 
Fecha de Ingreso: enero-2002
Ubicación: Santiago - Chile
Mensajes: 34.417
Antigüedad: 22 años, 2 meses
Puntos: 129
Pero .. de donde la sacastes? .. algún link? ... tal vez por ahí esté algún ejemplo.

Realmente sin ver ejemplo .. sería cosa de entrar a "probar". Para eso tendrías primero que nada "instanciar" el objeto y de ahí usar sus métodos como ahí más o menos describen lo que hacen .. Pero así seguro que no le "sacamos" el máximo provecho a dicha classe (con el tiempo y pruebas .. tal vez ..)

Un saludo,
  #7 (permalink)  
Antiguo 04/03/2005, 12:04
 
Fecha de Ingreso: agosto-2004
Mensajes: 258
Antigüedad: 19 años, 7 meses
Puntos: 0
De acuerdo

haya, hummm boy rebuscar mas mis archivos derrepente encuentro algun enlace... y lo poesteo....
  #8 (permalink)  
Antiguo 10/03/2005, 17:17
 
Fecha de Ingreso: agosto-2004
Mensajes: 258
Antigüedad: 19 años, 7 meses
Puntos: 0
Exclamación

Como lo dije CLUSTER, por fin encontre de donde lo habia sacado pero no tiene ningun otro enlace de referencia, aca te dejo el enlace espero me ayudes a entenderlo...
Código PHP:
http://www.xlwebmasters.com/modules.php?d=doc&f=doc&num=10&sec=2&subsec=80 
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 03:04.