Club Builder - Foros de discusión Club Builder
Foro de C++Builder en español
 
 FAQFAQ   BuscarBuscar   MiembrosMiembros   Grupos de UsuariosGrupos de Usuarios   RegistrarseRegistrarse 
 PerfilPerfil   Entra para ver tus mensajes privadosEntra para ver tus mensajes privados   EntrarEntrar 

crear un archivo de Excel

 
Publicar nuevo tema   Responder al tema    Foros de discusión -> Consultas
Ver tema anterior :: Ver tema siguiente  
Autor Mensaje
Mensaje    Asunto: crear un archivo de Excel Responder citando

HOLA!!!

Tengo un problema... hay un programa que yo estoy haciendo en el cual me genera un archivo .txt a partir de un DBGrind. Es asi:

arch.open("Cuenta diaria de tarjetas.txt",ios::out);
arch<<"Cuenta diaria de tarjetas"<<endl;
arch<<endl;

for (int i=1;i<=t->RecordCount;i++)
{f=t->FieldValues["FECHA"];
if (fec==f)
{tot+=StrToInt(t->FieldValues["CANTIDAD"]);

AnsiString can=t->FieldValues["CANTIDAD"];
char finc[200];
char finf[200];

strcpy(finc,can.c_str());
strcpy(finf,f.c_str());

arch<<finf<<" "<<finc<<endl;
}
t->Next();
}

y me sale asi:

Cuenta diaria de tarjetas

nombre ID tiempo
nombre ID tiempo
nombre ID tiempo
nombre ID tiempo
nombre ID tiempo

lo que yo necesito hacer es que me haga un archivo de Excel en vez de un txt.¨

GRACIAS!!!!
Volver arriba
Ver perfil de usuario Enviar mensaje privado
Mensaje    Asunto: Responder citando

Te dejo un codigo que exporta los datos de un dbgrid a un fichero de excel.
Te comento que lo que buscas, está ampliamente comentado en el foro, busca por excel.
Código:

Variant vExcel, vHoja, vRango;

    vExcel=CreateOleObject("Excel.Application");
    vExcel.OlePropertySet("Visible",true);
    vExcel.OlePropertyGet("Workbooks").OleProcedure("Add");
    vHoja=vExcel.OlePropertyGet("ActiveSheet");
     int row = 1;
     String COLUMNA = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";//para los nombres de columna


     //cabeceras
        for (int i = 0; i < qry->FieldDefs->Count; i++)
                {
                TFieldDef *fd = qry->FieldDefs->Items[i];
                if(i<=25)
                   vExcel.OlePropertyGet("Range",COLUMNA.SubString(i+1,1)+IntToStr(row)).OleProcedure("Select");
                if(i>25 && i <=51)
                   vExcel.OlePropertyGet("Range","A"+COLUMNA.SubString(i+1-26,1)+IntToStr(row)).OleProcedure("Select");
                if(i>51 && i <=77)
                   vExcel.OlePropertyGet("Range","B"+COLUMNA.SubString(i+1-26,1)+IntToStr(row)).OleProcedure("Select");
                if(i>77 && i <=103)
                   vExcel.OlePropertyGet("Range","C"+COLUMNA.SubString(i+1-78,1)+IntToStr(row)).OleProcedure("Select");
                vExcel.OlePropertyGet("ActiveCell").
               OlePropertySet("Value",fd->Name);
                }


     row++;
     row++;
     qry->First();
     while(!qry->Eof)
        {
        for(int col=0;col<qry->FieldCount;col++)
                {
                if(col<=25)
                vExcel.OlePropertyGet("Range",COLUMNA.SubString(col+1,1)+IntToStr(row)).OleProcedure("Select");
                if(col>25 && col <=51)//if(col>26 <=52)
                vExcel.OlePropertyGet("Range","A"+COLUMNA.SubString(col+1-26,1)+IntToStr(row)).OleProcedure("Select");
                if(col>51 && col <=77)
                vExcel.OlePropertyGet("Range","B"+COLUMNA.SubString(col+1-52,1)+IntToStr(row)).OleProcedure("Select");
                if(col>77 && col <=103)
                vExcel.OlePropertyGet("Range","C"+COLUMNA.SubString(col+1-78,1)+IntToStr(row)).OleProcedure("Select");
                vExcel.OlePropertyGet("ActiveCell").
                OlePropertySet("Value",qry->Fields->Fields[col]->AsString);
                }
        qry->Next();
        row++;
        }

    vExcel=vHoja=Unassigned;


Si tienes algún problema, ya sabes.
_________________
Un saludo
Rayder
Volver arriba
Ver perfil de usuario Enviar mensaje privado
Mensaje    Asunto: Responder citando

Despues de largo tiempo, me he decicido a poner datos de un TListView a Excel.
Visto el ejemplo que has pasado, lo he probado y no funciona: da el error tipo de variable incorrecto.
Código:

vExcel.OlePropertyGet("Range",COLUMNA.SubString(i+1,1)+IntToStr(row)).
                    OleProcedure("Select"


He mirado en los foros y dicen que la variable no puede ansistring, por lo cual he hecho esto
Código:

                AnsiString columna;
 
                if(i<=25){
                   columna=COLUMNA.SubString(i+1,1)+IntToStr(row);                                     
                   vExcel.OlePropertyGet("Range",columna.c_str()).
                                              OleProcedure("Select");
                  }


Y tampoco. He vuelvo a leer los post sobre excel (un monton) y alguien decia esto
Código:

                AnsiString columna;
                char *puntero;
                if(i<=25){
                   columna=COLUMNA.SubString(i+1,1)+IntToStr(row);               
                   puntero=columna.c_str();
                   Excel.OlePropertyGet("Range",puntero).
                                           OleProcedure("Select");
               }

Y como antes. Siempre da error de tipo de variable al ejecutar la linea.

¿Alguien que le funcione?

Saludos, Bosoft.
Volver arriba
Ver perfil de usuario Enviar mensaje privado
Mensaje    Asunto: Responder citando

Te puedo mandar un ejemplo compilado por email.
No obstante, te pongo el código completo del ejemplo

Unit1.cpp
Código:

//---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop

#include <Comobj.hpp> // para formater las celdas de excel

#include "Unit1.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "Excel_2K_SRVR"
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
        : TForm(Owner)
{
}
//---------------------------------------------------------------------------

void __fastcall TForm1::Button1Click(TObject *Sender)
{
Variant vExcel, vHoja, vRango;

    vExcel=CreateOleObject("Excel.Application");
    vExcel.OlePropertySet("Visible",true);
    vExcel.OlePropertyGet("Workbooks").OleProcedure("Add");
    vHoja=vExcel.OlePropertyGet("ActiveSheet");
     int row = 1;
     String COLUMNA = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";//para los nombres de columna


     //cabeceras
        for (int i = 0; i < qry->FieldDefs->Count; i++)
                {
                TFieldDef *fd = qry->FieldDefs->Items[i];
                if(i<=25)
                   vExcel.OlePropertyGet("Range",COLUMNA.SubString(i+1,1)+IntToStr(row)).OleProcedure("Select");
                if(i>25 && i <=51)
                   vExcel.OlePropertyGet("Range","A"+COLUMNA.SubString(i+1-26,1)+IntToStr(row)).OleProcedure("Select");
                if(i>51 && i <=77)
                   vExcel.OlePropertyGet("Range","B"+COLUMNA.SubString(i+1-26,1)+IntToStr(row)).OleProcedure("Select");
                if(i>77 && i <=103)
                   vExcel.OlePropertyGet("Range","C"+COLUMNA.SubString(i+1-78,1)+IntToStr(row)).OleProcedure("Select");
                vExcel.OlePropertyGet("ActiveCell").
               OlePropertySet("Value",fd->Name);
                }


     row++;
     row++;
     qry->First();
     while(!qry->Eof)
        {
        for(int col=0;col<qry->FieldCount;col++)
                {
                if(col<=25)
                vExcel.OlePropertyGet("Range",COLUMNA.SubString(col+1,1)+IntToStr(row)).OleProcedure("Select");
                if(col>25 && col <=51)//if(col>26 <=52)
                vExcel.OlePropertyGet("Range","A"+COLUMNA.SubString(col+1-26,1)+IntToStr(row)).OleProcedure("Select");
                if(col>51 && col <=77)
                vExcel.OlePropertyGet("Range","B"+COLUMNA.SubString(col+1-52,1)+IntToStr(row)).OleProcedure("Select");
                if(col>77 && col <=103)
                vExcel.OlePropertyGet("Range","C"+COLUMNA.SubString(col+1-78,1)+IntToStr(row)).OleProcedure("Select");
                vExcel.OlePropertyGet("ActiveCell").
                OlePropertySet("Value",qry->Fields->Fields[col]->AsString);
                }
        qry->Next();
        row++;
        }

    vExcel=vHoja=Unassigned;
}
//---------------------------------------------------------------------------

void __fastcall TForm1::FormShow(TObject *Sender)
{
Table1->Active = true;
qry->Active = true;

}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button2Click(TObject *Sender)
{
Application->Terminate();

}
//---------------------------------------------------------------------------


Unit.h
Código:

//---------------------------------------------------------------------------

#ifndef Unit1H
#define Unit1H
//---------------------------------------------------------------------------
#include <Classes.hpp>
#include <Controls.hpp>
#include <StdCtrls.hpp>
#include <Forms.hpp>
#include <Db.hpp>
#include <DBGrids.hpp>
#include <DBTables.hpp>
#include <Grids.hpp>
#include "Excel_2K_SRVR.h"
#include <OleServer.hpp>
#include <ExtCtrls.hpp>
//---------------------------------------------------------------------------
class TForm1 : public TForm
{
__published:   // IDE-managed Components
        TButton *Button1;
        TQuery *qry;
        TDBGrid *DBGrid1;
        TTable *Table1;
        TDataSource *DataSource1;
        TExcelGlobal *ExcelGlobal1;
        TAutoIncField *Table1Contador;
        TStringField *Table1Nombre;
        TStringField *Table1Apellido1;
        TStringField *Table1Apellido;
        TButton *Button2;
        TDBGrid *DBGrid2;
        TBevel *Bevel1;
        TLabel *Label2;
        TBevel *Bevel2;
        TLabel *Label1;
        TDataSource *DataSource2;
        void __fastcall Button1Click(TObject *Sender);
        void __fastcall FormShow(TObject *Sender);
        void __fastcall Button2Click(TObject *Sender);
private:   // User declarations
public:      // User declarations
        __fastcall TForm1(TComponent* Owner);
};
//---------------------------------------------------------------------------
extern PACKAGE TForm1 *Form1;
//---------------------------------------------------------------------------
#endif


Utilizo builder 5 professional con update pack 1

Lo he compilado y va sin problemas.Los datos los tengo en una tabla paradox, datos.db
Los componentes que uso, sobre un solo formulario:
Código:

2 TDBGrid
2 TDataSource
1 TTable1
1 Tqry
1 TExcelGlobal
2 Tbutton
2 TLabel
2 TBevel

_________________
Un saludo
Rayder
Volver arriba
Ver perfil de usuario Enviar mensaje privado
Mensaje    Asunto: Responder citando

Gracias ante todo por contestarme.
Yo quiero traspasar de un TListView a excel. Por lo tanto he quitado todo lo referente a datos y los he cambiado por los del TListView.

Eso va todo correcto. Compila sin problemas pero al ejecutarse en la linea que te indico arriba da el error de tipo de variable. Esa linea, de una forma o de otra, esta repetida varias veces y en todas dará error.

Yo uso builder 6 con update 4.
Revisando tu codigo he visto #include "Excel_2K_SRVR.h" . Voy a probar por si acaso

Saludos y gracias

edito: sigue sin funcionar. Da error de tipo de variable.

¿Alguien tiene la solucion?

Edito de nuevo: Ya funciona.
hay que agregar estas lineas
Código:
#include "Excel_2K_SRVR.h"
#include <OleServer.hpp>

y en cada linea del error
Código:
                   columna=COLUMNA.SubString(i+1,1)+IntToStr(row);
                   vExcel.OlePropertyGet("Range",columna.c_str()).OleProcedure("Select");


Gracias y Saludos, Bosfot

PD: si alguien quiere el codigo de pasar el TListView a Excel, pos lo pongo
Volver arriba
Ver perfil de usuario Enviar mensaje privado
Mensaje    Asunto: Responder citando

Mira el codigo de "arriba" codigo funcionaba perfectamente bien en mis programas.

Luego por algua razon desconocida empezo a marcar error (no lo toque), me fastidie de cambair encabezados, reinstalar office etc etc

Asi que tome otro enfoque e hice este:

Código:
//--------------------------------------
void QueryToCSV(TTable *qry,AnsiString sArchivo)
{

 int Index;
  TStringList* MyList = new TStringList();

 while (!qry->Eof)
  {
  AnsiString sRenglon="";
  for(int col=0;col<qry->FieldCount;col++)
      sRenglon=sRenglon+qry->Fields->Fields[col]->AsString+",";
  MyList->Add(sRenglon);
  qry->Next();
  }
  MyList->SaveToFile(sArchivo);
    delete MyList;

}


Te convierte cuealquier table a un archvio separado por "," que lo peude leer excel, puedes sobrecargar la funcion y cambiar el TTable por TQuery.

Si mejoras el codigo te ruego lo pongas de nuevo para ayudar a todo aquel que lo necesite

Pero tambien y alei el tuyo (el primer port) solo agregale "," entre campos y campo y excel lo lee perfectamete , la extension el archivo en lugar de txt ponle CSV
_________________
Ing. Gabriel Góngora Navarrete
TouchSoftwares Inc

http://www.touchsoftwares.com
Volver arriba
Ver perfil de usuario Enviar mensaje privado Visitar sitio web del autor MSN Messenger
Mensaje    Asunto: Responder citando

precisamente quiero evitar ese paso. Hasta ahora lo habia hecho pasando a un txt separado por ';' y entre comillas porque en el texto suelen haber comas que confunden al excel.
Ahora solo tengo que guardar desde el excel abierto por mi programa.

te paso el codigo completo de traspaso a excel desde un TListView.

el nombre del TListView es remesa. El resto es autonomo
en la cabecera debes poner
Código:
#include <comobj.hpp>
#include "Excel_2K_SRVR.h"
#include <OleServer.hpp>

y la funcion es:
Código:
void __fastcall Temision::Button10Click(TObject *Sender)
{
Variant vExcel, vHoja, vRango;
TListItem *Elemento;
AnsiString Valor;
    vExcel=CreateOleObject("Excel.Application");
    vExcel.OlePropertySet("Visible",true);
    vExcel.OlePropertyGet("Workbooks").OleProcedure("Add");
    vHoja=vExcel.OlePropertyGet("ActiveSheet");
     int row = 1;
     String COLUMNA = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";//para los nombres de columna

     //cabeceras
        for (int i = 0; i < remesa->Columns->Count; i++)
                {

                AnsiString columna;
                Valor= remesa->Columns->Items[i]->Caption;

                if(i<=25){
                   columna=COLUMNA.SubString(i+1,1)+IntToStr(row);
                   vExcel.OlePropertyGet("Range",columna.c_str()).OleProcedure("Select");
                   }
                if(i>25 && i <=51){
                   columna="A"+COLUMNA.SubString(i+1-26,1)+IntToStr(row);
                   vExcel.OlePropertyGet("Range",columna.c_str()).OleProcedure("Select");
                   }
                if(i>51 && i <=77){
                   columna="B"+COLUMNA.SubString(i+1-26,1)+IntToStr(row);
                   vExcel.OlePropertyGet("Range",columna.c_str()).OleProcedure("Select");
                   }
                if(i>77 && i <=103){
                   columna="C"+COLUMNA.SubString(i+1-78,1)+IntToStr(row);
                   vExcel.OlePropertyGet("Range",columna.c_str()).OleProcedure("Select");
                   }
                vExcel.OlePropertyGet("ActiveCell").
                OlePropertySet("Value",Valor.c_str());
                }
     row++;
// datos
for(int i=0;i<remesa->Items->Count;i++){
        for(int col=0;col<remesa->Columns->Count;col++) {
                AnsiString columna;
                Elemento=remesa->Items->Item[i];

                if(col<=25){
                   columna=COLUMNA.SubString(col+1,1)+IntToStr(row);
                   vExcel.OlePropertyGet("Range",columna.c_str()).OleProcedure("Select");
                   }
                if(col>25 && col <=51){
                   columna="A"+COLUMNA.SubString(col+1-26,1)+IntToStr(row);
                   vExcel.OlePropertyGet("Range",columna.c_str()).OleProcedure("Select");
                   }
                if(col>51 && col <=77){
                   columna="B"+COLUMNA.SubString(col+1-26,1)+IntToStr(row);
                   vExcel.OlePropertyGet("Range",columna.c_str()).OleProcedure("Select");
                   }
                if(col>77 && col <=103){
                   columna="C"+COLUMNA.SubString(col+1-78,1)+IntToStr(row);
                   vExcel.OlePropertyGet("Range",columna.c_str()).OleProcedure("Select");
                   }
                if(!col) Valor=Elemento->Caption;
                else Valor=Elemento->SubItems->Strings[col-1];
                vExcel.OlePropertyGet("ActiveCell").OlePropertySet("Value",Valor.c_str());
                }
        row++;
        }
    vExcel=vHoja=Unassigned;
}

Como te habras dado cuenta la funcion esta dentro de un clic a button10

Espero que os funcione tan bien como a mi.

Saludos, Bosoft.
Volver arriba
Ver perfil de usuario Enviar mensaje privado
Mostrar mensajes de anteriores:   
Cambiar a:  
No puedes publicar temas nuevos en este foro
No puedes responder a temas en este foro
No puedes editar tus mensajes en este foro
No puedes borrar tus mensajes en este foro
No puedes votar en las encuestas de este foro


Hosting WordPress Indedmedia desde 3,99 €
© 2002–2026 Club Builder · Funciona con phpBB.