# Exportar datos a excell

**URL:** <https://www.ruby-forum.com/t/exportar-datos-a-excell/170878>\
**Category:** ES\
**Created:** [June 23, 2009, 10:09pm UTC](https://www.ruby-forum.com/t/exportar-datos-a-excell/170878 "2009-06-23T22:09:48Z")\
**Posts on this page:** 8\
**Page:** 1

<div class="post-metadata">

**Author:** ![alex123](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/ecd19e/32.png) [@alex123](https://www.ruby-forum.com/u/alex123)\
**Post date:** [June 23, 2009, 10:09pm UTC](https://www.ruby-forum.com/t/exportar-datos-a-excell/170878/1 "2009-06-23T22:09:48Z")

</div>

Hola

En estos dias he estado tratando de exportar unos datos a csv pero tengo  
un problema es demasiada informaciÃ³n y habeces se queda mucho tiempo y  
nunca exporta, otra es que muchas veces el mongrel muere y el mensaje es  
que ha terminado por una causa desconocida.

Como puedo hacer para que no se cuelgue el servidor y para que la  
exportaciÃ³n sea mas ligera.

Gracias

---

<div class="post-metadata">

**Author:** ![alex123](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/ecd19e/32.png) [@alex123](https://www.ruby-forum.com/u/alex123)\
**Post date:** [June 24, 2009, 2:48am UTC](https://www.ruby-forum.com/t/exportar-datos-a-excell/170878/2 "2009-06-24T02:48:08Z")

</div>

Podrías pegar [1] el código que tienes para poder ayudarte?

1- [http://pastie.org/](http://pastie.org/)

2009/6/23 Jhony A. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid):

---

<div class="post-metadata">

**Author:** ![alex123](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/ecd19e/32.png) [@alex123](https://www.ruby-forum.com/u/alex123)\
**Post date:** [June 24, 2009, 3:30pm UTC](https://www.ruby-forum.com/t/exportar-datos-a-excell/170878/3 "2009-06-24T15:30:39Z")

</div>

Â¿CuÃ¡nto le cuesta ejecutar cada consulta? Si el problema no es el tiempo  
de ejecuciÃ³n de las consultas yo probarÃ­a a usar FasterCSV en vez de  
CSV::Writer porque me da a mi que CSV::Writer es lentillo(de ahÃ­ el  
nombre de la gema).

Suerte

Jhony A. wrote:

> En el controlador tengo esto  
> JOIN PROJECTS P  
> LEFT JOIN CUSTOM\_VALUES F  
> end  
> :type =\> ‘text/csv; header=present’, :filename =\> ‘export.csv’) }  
> CSV::Writer.generate(export, l(:general\_csv\_separator)) do |csv|  
> AND i.project\_id = #{issue[‘id’]}  
> total=(total.to\_f).round(2)
> 
> ```
> "T.Estimado",
> fields = [issue['actividad'],
> issue['comentario'],
> "",
> ""]
> 
> ```
> 
> Gracias por cualquier ayuda

–  
Rafa

---

<div class="post-metadata">

**Author:** ![alex123](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/ecd19e/32.png) [@alex123](https://www.ruby-forum.com/u/alex123)\
**Post date:** [June 24, 2009, 3:13pm UTC](https://www.ruby-forum.com/t/exportar-datos-a-excell/170878/4 "2009-06-24T15:13:59Z")

</div>

Ceritium wrote:

> Podrï¿½as pegar [1] el cï¿½digo que tienes para poder ayudarte?
> 
> 1- [http://pastie.org/](http://pastie.org/)
> 
> 2009/6/23 Jhony A. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid):

En el controlador tengo esto

# el sql

sql=“SELECT  
p.name’project’,i.project\_id’id’,i.id’tid’,i.id’tarea\_id’,concat(firstname,’  
‘,lastname)‘nombre’,subject’actividad’,g.NOMBRE  
‘gerencia’,c.value’aplicacion’,f.value’planeada’,I.CCOSTOS’ccosto’,estimated\_hours  
‘Estimado’,hours’Dedicado’,spent\_on’freporte’,comments’comentario’,done\_ratio’ejecucion’,e.name’facturable’,i.due\_date’termina’,i.start\_date’comienza’,it.name’estado’  
FROM TIME\_ENTRIES T LEFT JOIN ISSUES I  
ON T.ISSUE\_ID=I.ID,  
JOIN ISSUE\_STATUSES IT  
ON IT.ID=I.STATUS\_ID  
JOIN PROJECTS P  
ON T.PROJECT\_ID=P.ID  
LEFT JOIN GERENCIAS G  
ON I.GERENCIA\_ID=G.ID  
JOIN ENUMERATIONS E  
ON E.ID=T.ACTIVITY\_ID  
JOIN USERS U  
ON T.USER\_ID=U.ID  
LEFT JOIN CUSTOM\_VALUES C  
ON T.ISSUE\_ID=C.CUSTOMIZED\_ID  
AND C.CUSTOM\_FIELD\_ID=43  
LEFT JOIN CUSTOM\_VALUES F  
ON T.ISSUE\_ID=F.CUSTOMIZED\_ID  
AND F.CUSTOM\_FIELD\_ID=40 "  
sql \<\< " WHERE I.PROJECT\_ID in (#{@projects.join(‘,’)})  
AND T.USER\_ID in (#{@users.join(‘,’)})”  
sql \<\<" AND T.SPENT\_ON \>= (‘%s’)" % @date\_from  
sql \<\<" AND T.SPENT\_ON \<= (‘%s’)" % @date\_to  
sql \<\<" AND i.status\_id in (#{@issues\_status.join(‘,’)})"  
sql \<\< " AND t.activity\_id in (#{@activities.join(‘,’)})"  
if @gerencia != “”  
sql \<\< " AND g.id = %s"%@gerencia  
end  
if @aplicacion[0] != ‘-1’  
sql \<\< " AND c.value = (‘%s’)“%@aplicacion  
end  
sql\<\<” order by 2,5,13"

```
  @issues = ActiveRecord::Base.connection.select_all(sql)

```

# El metodo para exportar a csv

```
respond_to do |format|
    format.csv { 

```

send\_data(issues\_to\_csv(@issues,@users,@date\_from,@date\_to,@activities,@estimado,@totalf).read,  
:type =\> ‘text/csv; header=present’, :filename =\> ‘export.csv’) }  
end

#En el helper tengo esto.

def issues\_to\_csv(issues,users,from,to,activities,estimado,totalf)  
@projects=“”  
ic = Iconv.new(l(:general\_csv\_encoding), ‘UTF-8’)  
decimal\_separator = l(:general\_csv\_decimal\_separator)  
export = StringIO.new  
CSV::Writer.generate(export, l(:general\_csv\_separator)) do |csv|

```
  issues.each do |issue|

  # Por cada proyecto debo sumar unas horas estimadas.
  if issue['id'] != @projects
    csv << ''
    sql="SELECT sum(hours)'hours'
      FROM time_entries t, issues i
      WHERE i.id=t.issue_id
      AND t.user_id in (#{users.join(',')})
      AND i.project_id = #{issue['id']}
      AND t.activity_id in (#{activities.join(',')})
      AND t.spent_on >= ('#{from}')
      AND t.spent_on <= ('#{to}')
        GROUP BY i.project_id"
     total=0
          @total = ActiveRecord::Base.connection.select_all(sql)
          @total.each do |z|
            total = z['hours'].to_f
          end

    total=(total.to_f).round(2)

    @projects=issue['id']
    projects = [issue['project'],
                   total,
                   l(:field_hours)
                   ]
    csv << projects.collect {|c| begin; ic.iconv(c.to_s); rescue; 

```

c.to\_s; end }  
csv \<\< ‘’  
end

```
  # cabeceras.

  headers = [ l(:field_subject),
                   "F.Inicio",
                   "F.Fin",
                   l(:field_status),
                   l(:informe_gerencia_label),
                   l(:informe_aplicacion_label),
                   "C.C",
                   "Planeada",
                   "T.Estimado",
                   "T.Dedicado",
                   "F.Reporte",
                   "Detalle",
                   "Facturable",
                   l(:field_assigned_to),
              ]

  csv << headers.collect {|c| begin; ic.iconv(c.to_s); rescue; 

```

c.to\_s; end }  
#tareas  
fields = [issue[‘actividad’],  
issue[‘comienza’],  
issue[‘termina’],  
issue[‘estado’],  
issue[‘gerencia’],  
issue[‘aplicacion’],  
issue[‘ccosto’],  
issue[‘planeada’],  
issue[‘Estimado’],  
issue[‘Dedicado’],  
issue[‘freporte’],  
issue[‘comentario’],  
issue[‘facturable’],  
issue[‘nombre’]  
]

```
    csv << fields.collect {|c| begin; ic.iconv(c.to_s); rescue; 

```

c.to\_s; end }

```
  end
  totales=["",
               "",
               "",
               "",
               "",
               "",
               "",
               "",
              estimado,
              totalf,
              "",
              "",
              "",
              ""]
    csv << totales.collect {|c| begin; ic.iconv(c.to_s); rescue; 

```

## c.to\_s; end } end export.rewind export end

En el momento se estan recibiendo desde las bd 20.000 registros y esto  
tiende a aumentar

Gracias por cualquier ayuda

---

<div class="post-metadata">

**Author:** ![alex123](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/ecd19e/32.png) [@alex123](https://www.ruby-forum.com/u/alex123)\
**Post date:** [June 24, 2009, 4:33pm UTC](https://www.ruby-forum.com/t/exportar-datos-a-excell/170878/5 "2009-06-24T16:33:27Z")

</div>

Excel o CSV? para excel mirate [http://spreadsheet.rubyforge.org/](http://spreadsheet.rubyforge.org/)

Yo lo utilizo en varios proyectos y me va muy bien.

Para CSV FasterCSV, como te han recomendado, tambiÃ©n estÃ¡ muy bien.

Otra recomendaciÃ³n, no cargues tanto los controladores, mete todo lo que  
puedas en los modelos, clases propias y mÃ³dulos y en los controladores  
utiliza respond\_to

def show  
@issue = Issue.find…  
respond\_to do |format|  
format.html  
format.xml {…}  
format.csv { @issue.to\_csv } # el to\_csv lo tendrÃ­as que implementar  
format.xls { @issue.to\_xls } # o algo como MyXLSClass.export(@issue)  
format.pdf { @issue.to\_pdf } #  
format.png { @issue.to\_png } #  
end  
end

sds

Jorge

---

<div class="post-metadata">

**Author:** ![alex123](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/ecd19e/32.png) [@alex123](https://www.ruby-forum.com/u/alex123)\
**Post date:** [June 25, 2009, 6:51am UTC](https://www.ruby-forum.com/t/exportar-datos-a-excell/170878/6 "2009-06-25T06:51:58Z")

</div>

Hola estuve haciendo pruebas de performance con fastercsv y la  
exportacion de 36131 filas se demoro 1 minuto con 40 segundos.

Mejoro mucho el tiempo de respuesta y el servidor no se muere.

Muchas gracias por todo

Otra pregunta  
esto esta en el metodo de exportacion  
ic = Iconv.new(‘ISO-8859-15’, ‘UTF-8’)  
decimal\_separator = l(:general\_csv\_decimal\_separator)  
export = FasterCSV.generate(:col\_sep =\> l(:general\_csv\_separator))  
do |csv|

y muchos de los datos que son exportados tienen tilde, el problema es  
que muchos de estos quedan con la tilde bien pero otros quedan con los  
caracteres rraros pero yo pensaba que con iconv este error no volveria a  
pasar pero esto ya fue algo demasiado raro que formateara algunos datos  
y otros no

Muchas gracias por toda la ayuda que me han dado hacerca del tema.

---

<div class="post-metadata">

**Author:** ![alex123](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/ecd19e/32.png) [@alex123](https://www.ruby-forum.com/u/alex123)\
**Post date:** [June 25, 2009, 5:51am UTC](https://www.ruby-forum.com/t/exportar-datos-a-excell/170878/7 "2009-06-25T05:51:54Z")

</div>

Rafael GarcÃ­a wrote:

> Â¿CuÃ¡nto le cuesta ejecutar cada consulta? Si el problema no es el tiempo  
> de ejecuciÃ³n de las consultas yo probarÃ­a a usar FasterCSV en vez de  
> CSV::Writer porque me da a mi que CSV::Writer es lentillo(de ahÃ­ el  
> nombre de la gema).
> 
> Suerte
> 
> Jhony A. wrote:
> 
> > En el controlador tengo esto  
> > JOIN PROJECTS P  
> > LEFT JOIN CUSTOM\_VALUES F  
> > end  
> > :type =\> ‘text/csv; header=present’, :filename =\> ‘export.csv’) }  
> > CSV::Writer.generate(export, l(:general\_csv\_separator)) do |csv|  
> > AND i.project\_id = #{issue[‘id’]}  
> > total=(total.to\_f).round(2)
> > 
> > ```
> > "T.Estimado",
> > fields = [issue['actividad'],
> > issue['comentario'],
> > "",
> > ""]
> > 
> > ```
> > 
> > Gracias por cualquier ayuda

Gracias por la respuesta,

Tienen algun ejemplo sencillo de como utilizar fastercsv

Gracias

> > 
> 
> –  
> Rafa

---

<div class="post-metadata">

**Author:** ![alex123](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/ecd19e/32.png) [@alex123](https://www.ruby-forum.com/u/alex123)\
**Post date:** [June 25, 2009, 6:59am UTC](https://www.ruby-forum.com/t/exportar-datos-a-excell/170878/8 "2009-06-25T06:59:24Z")

</div>

Jhony A. wrote:

> Tienen algun ejemplo sencillo de como utilizar fastercsv

[http://fastercsv.rubyforge.org/classes/FasterCSV.html](http://fastercsv.rubyforge.org/classes/FasterCSV.html)
