Marcelo eu utilizo desta forma a Thread

unit u_importacao;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, u_default, StdCtrls, Buttons, ExtCtrls, Gauges, ComCtrls, Grids,
  DBGrids, DB, DBClient, strutils, FMTBcd, dateUtils, ADODB;

Type
  Registro = record
    nome :String;
    tamanho :Byte;
    precisao :byte;
  end;

  Tfrm_importacao = class(Tfrm_default)
    gb_advertencias: TGroupBox;
    mm_advertencias: TMemo;
    gb_demonstrativos: TGroupBox;
    gb_analise: TGroupBox;
    gau_analise: TGauge;
    OD: TOpenDialog;
    gb_registros: TGroupBox;
    gb_regsaldos: TGroupBox;
    gb_regempenhos: TGroupBox;
    grid_empenhos: TDBGrid;
    grid_saldos: TDBGrid;
    cds_saldos: TClientDataSet;
    ds_saldos: TDataSource;
    ds_empenhos: TDataSource;
    cds_saldosITCOUNIDADEGESTORA: TStringField;
    cds_saldosITCOGESTAO: TStringField;
    cds_saldosGRCODIGOCONTA: TStringField;
    cds_saldosITCOCONTACORRENTECONTABIL: TStringField;
    cds_saldosITVADEBITOINICIAL: TFMTBCDField;
    cds_saldosITVACREDITOINICIAL: TFMTBCDField;
    Pan_geral: TPanel;
    gb_arquivos: TGroupBox;
    SpeedButton1: TSpeedButton;
    Label1: TLabel;
    edt_caminho: TEdit;
    mm_arquivos: TMemo;
    gb_inform: TGroupBox;
    cb_exercicio: TComboBox;
    Label2: TLabel;
    cds_empenhos: TClientDataSet;
    cds_empenhosGRUGGESTAOANNUMERONEUQ: TStringField;
    cds_empenhosITDAEMISSAO: TStringField;
    cds_empenhosITINFAVORECIDO: TStringField;
    cds_empenhosITCOFAVORECIDO: TStringField;
    cds_empenhosGRCODIGOEVENTO: TStringField;
    cds_empenhosITCOPROGRAMATRABALHORESUMID: TStringField;
    cds_empenhosGRFONTERECURSO: TStringField;
    cds_empenhosGRNATUREZADESPESA: TStringField;
    cds_empenhosITVATRANSACAO: TFMTBCDField;
    cds_saldosITVADEBITOMENSAL1: TFMTBCDField;
    cds_saldosITVACREDITOMENSAL1: TFMTBCDField;
    cds_saldosITVADEBITOMENSAL2: TFMTBCDField;
    cds_saldosITVACREDITOMENSAL2: TFMTBCDField;
    cds_saldosITVADEBITOMENSAL3: TFMTBCDField;
    cds_saldosITVACREDITOMENSAL3: TFMTBCDField;
    cds_saldosITVADEBITOMENSAL4: TFMTBCDField;
    cds_saldosITVACREDITOMENSAL4: TFMTBCDField;
    cds_saldosITVADEBITOMENSAL5: TFMTBCDField;
    cds_saldosITVACREDITOMENSAL5: TFMTBCDField;
    cds_saldosITVADEBITOMENSAL6: TFMTBCDField;
    cds_saldosITVACREDITOMENSAL6: TFMTBCDField;
    cds_saldosITVADEBITOMENSAL7: TFMTBCDField;
    cds_saldosITVACREDITOMENSAL7: TFMTBCDField;
    cds_saldosITVADEBITOMENSAL8: TFMTBCDField;
    cds_saldosITVACREDITOMENSAL8: TFMTBCDField;
    cds_saldosITVADEBITOMENSAL9: TFMTBCDField;
    cds_saldosITVACREDITOMENSAL9: TFMTBCDField;
    cds_saldosITVADEBITOMENSAL10: TFMTBCDField;
    cds_saldosITVACREDITOMENSAL10: TFMTBCDField;
    cds_saldosITVADEBITOMENSAL11: TFMTBCDField;
    cds_saldosITVACREDITOMENSAL11: TFMTBCDField;
    cds_saldosITVADEBITOMENSAL12: TFMTBCDField;
    cds_saldosITVACREDITOMENSAL12: TFMTBCDField;
    lbl_analise: TLabel;
    procedure btn_fecharClick(Sender: TObject);
    procedure SpeedButton1Click(Sender: TObject);
    procedure btn_procurarClick(Sender: TObject);
    procedure btn_cancelarClick(Sender: TObject);
    procedure FormCreate(Sender: TObject);
    procedure btn_novoClick(Sender: TObject);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
    procedure FormShow(Sender: TObject);
    procedure btn_excluirClick(Sender: TObject);
    procedure btn_salvarClick(Sender: TObject);
  private
    { Private declarations }
    dataAtualizacao :TDateTime;
    Arquivos :TStringList;
    procedure CarregarArquivos(const Pasta: String; var Listagem: TStringList);
  public
    { Public declarations }
  end;


  TProcessos = class(TThread)
  private
      fSaldos, fEmpenhos :TextFile;
      procedure atualizar(const i :word );
      procedure analisarDados(const caminho: String);
      procedure carregaRegistro(const linha: string; var campo: registro);
      procedure acertaCampo(var campo: String; const linha: String);
      function  temCampo(const CDS: TClientdataSet; const campo: String): 
boolean;
      procedure processaLinhaSaldo(const linha: String; Camp: array of 
registro);
      procedure processaLinhaEmpenho(const linha: String; Camp: array of 
registro);
      function acertaNomeCampo(const campo :String) :String;
  protected
      procedure Execute; override;
  public
      constructor Create;
  end;


  TImportaSaldo = class(TThread)
    private
      registrosAfetadosS  :integer;
      CDS  : Pointer;
      Progresso :TGauge;
      ADOC_Saldo :TADOConnection;
      procedure atualiza;
    protected
      procedure Execute; override;
    public
      constructor Create(const cdsSaldo: Pointer);
  end;

  TImportaEmpenho = class(TThread)
    private
      registrosAfetadosE :integer;
      CDSEmp  : Pointer;
      ProgressoEmp :TGauge;
      ADOC_Empenho :TADOConnection;
      procedure atualiza;
    protected
      procedure Execute; override;
    public
      constructor Create(const cdsEmpenho :Pointer);
  end;

  TFinalizaImportacao = class(TThread)
    private
      ADOC_Finaliza :TADOConnection;
      saOk, emOk :Pointer;
      texto :String;
      dataAtualiz :TDateTime;
      procedure atualizaLabel;
    protected
      procedure Execute; override;
    public
      constructor Create(const sOk, eOk :Pointer; const data :TDateTime);
  end;

var
  frm_importacao: Tfrm_importacao;
  Processos :TProcessos;

implementation
uses u_dm;

{$R *.dfm}

procedure Tfrm_importacao.btn_fecharClick(Sender: TObject);
begin
  inherited;
  close;
end;

procedure Tfrm_importacao.SpeedButton1Click(Sender: TObject);
begin
  inherited;
  OD.InitialDir := ExtractFileDir(Application.ExeName);
  if OD.Execute then
    edt_caminho.text := ExtractFilePath(od.FileName);
end;

Procedure Tfrm_importacao.CarregarArquivos(const Pasta :String; var Listagem 
:TStringList);
var SearchRec :TSearchRec;
begin
  dataAtualizacao := strtodatetime('01/01/1900');
  Listagem.Clear;
  if FindFirst(Pasta+'*.*',faAnyFile,SearchRec) = 0 then
  begin
    if FileExists(Pasta+SearchRec.Name) and (( 
UpperCase(ExtractFileExt(Pasta+SearchRec.Name)) = '.TXT') ) then
      if (Uppercase(Copy(SearchRec.Name,1,2)) = 'MC') or 
(Uppercase(Copy(SearchRec.Name,1,2)) = 'NE') or 
(UpperCase(Copy(SearchRec.Name,1,2)) = 'NF') then
      begin
        Listagem.Add(Pasta+SearchRec.Name);
        if ((Uppercase(Copy(SearchRec.Name,1,2)) = 'MC') ) then
          if (dataAtualizacao = null) or ( dataAtualizacao < 
strtodatetime(Copy(SearchRec.Name,5,2)+'/'+Copy(SearchRec.Name,3,2)+'/'+IntToStr(YearOf(dm.qry_data.FieldByName('Agora').asDateTime))))
 then
            dataAtualizacao := 
strtodatetime(Copy(SearchRec.Name,5,2)+'/'+Copy(SearchRec.Name,3,2)+'/'+IntToStr(YearOf(dm.qry_data.FieldByName('Agora').asDateTime)));
      end;
    while FindNext(SearchRec) = 0 do
    begin
      if FileExists(Pasta+SearchRec.Name) and (( 
UpperCase(ExtractFileExt(Pasta+SearchRec.Name)) = '.TXT')) then
        if (Uppercase(Copy(SearchRec.Name,1,2)) = 'MC') or 
(Uppercase(Copy(SearchRec.Name,1,2)) = 'NE') or 
(UpperCase(Copy(SearchRec.Name,1,2)) = 'NF') then
        begin
          Listagem.Add(Pasta+SearchRec.Name);
          if ((Uppercase(Copy(SearchRec.Name,1,2)) = 'MC') ) then
            if (dataAtualizacao = null) or ( dataAtualizacao < 
strtodatetime(Copy(SearchRec.Name,5,2)+'/'+Copy(SearchRec.Name,3,2)+'/'+IntToStr(YearOf(dm.qry_data.FieldByName('Agora').asDateTime))))
 then
              dataAtualizacao := 
strtodatetime(Copy(SearchRec.Name,5,2)+'/'+Copy(SearchRec.Name,3,2)+'/'+IntToStr(YearOf(dm.qry_data.FieldByName('Agora').asDateTime)));
        end;
    end;
  end;
  FindClose(SearchRec);
  Listagem.Sort;
end;

procedure Tfrm_importacao.btn_procurarClick(Sender: TObject);
begin
  inherited;
  lbl_analise.Visible := false;
  gau_analise.visible := true;
  btn_procurar.enabled := false;
  mm_advertencias.Clear;
  gau_analise.Progress := 0;  
  If (length(edt_caminho.text)>0) then
    CarregarArquivos(edt_caminho.text, Arquivos)
  else
    ShowMessage('Caminho não especificado.');
  MM_Arquivos.Lines.Text := Arquivos.Text;
end;

procedure Tfrm_importacao.btn_cancelarClick(Sender: TObject);
begin
  inherited;
  MM_arquivos.Lines.Clear;
  Arquivos.Clear;
  cds_saldos.first;
  while not cds_saldos.Eof do
    cds_saldos.delete;
  cds_empenhos.first;
  while not cds_empenhos.Eof do
    cds_empenhos.delete;
  btn_novo.enabled := true;
  btn_procurar.enabled := true;
  btn_excluir.Enabled := true;
end;

procedure Tfrm_importacao.FormCreate(Sender: TObject);
var i :smallint;
begin
  inherited;
  edt_caminho.Text := ExtractFilePath(Application.ExeName);
  cds_saldos.close;
  cds_saldos.FileName := ExtractFilePath(Application.ExeName)+'dbsaldos.xml';
  cds_empenhos.close;
  cds_empenhos.FileName := 
ExtractFilePath(Application.ExeName)+'dbempenhos.xml';
  Arquivos := TStringList.Create;
  cb_exercicio.Items.Clear;
  for i := -10 to 10 do
    cb_exercicio.Items.Add(InttoStr(yearof(Now())+i));
end;

function TProcessos.temCampo(const CDS :TClientdataSet; const campo :String 
):boolean;
begin
  result := true;
  if cds.FieldDefs.IndexOf(trim(copy(campo,1,31))) < 0 then
  begin
    result := false;
    frm_importacao.mm_advertencias.Lines.Add('Campo '+uppercase(campo)+' não 
encontrado!!');
  end;
end;

procedure TProcessos.acertaCampo(var campo :String; const linha :String);
begin
  campo := trim(copy(linha,1,40));
  if campo = 'GR-UG-GESTAO-AN-NUMERO-NEUQ(1)' then
    campo := 'GR-UG-GESTAO-AN-NUMERO-NEUQ';
end;

procedure TProcessos.carregaRegistro(const linha :string; var campo :registro );
var tmp :string;
begin
  campo.nome := trim(copy(linha,1,40));
  tmp := trim(copy(linha,42,5));
  if pos(',', tmp) > 0 then
  begin
    campo.precisao  := strtoint(copy(tmp, 1, pos(',', tmp)-1))
                      + strtoint(copy(  tmp, pos(',',tmp)+1,5-pos(',', tmp)));
    campo.tamanho := strtoint(copy(tmp, pos(',', tmp)+1, length(tmp)-pos(',', 
tmp)));
  end
  else
    campo.tamanho := strtoint(tmp);
end;

procedure TProcessos.analisarDados(const caminho :String );
var arquivo :TextFile;
    linha, campo  :string;
    i  :Word;
    campos :array of Registro;
begin
  //Saldos Contábeis
  if (UpperCase(copy(ExtractFileName(caminho),1,2))='MC') then
  Begin
    if not FileExists(copy(caminho,1, length(caminho)- 4) +'.ref') then
    begin
      frm_importacao.mm_advertencias.lines.add('Arquivo não encontrado: 
'+copy(caminho,1, length(caminho)- 4) +'.ref');
      exit;
    end;
    assignFile (arquivo,copy(caminho,1, length(caminho)- 4) +'.ref');
    try
      reset( arquivo );
      readLn( arquivo, linha );
      if length(linha) > 0 then
      begin
        i := 0;
        setLength(campos, length(campos)+1);
        TProcessos(self).carregaregistro(linha, campos[i]);
        inc(i);
        acertaCampo(campo, linha);
        if not (TProcessos(self).temCampo(frm_importacao.cds_saldos, campo)) 
then
          exit;
        while not Eof(arquivo) do
        begin
          readLn(arquivo,linha);
          acertaCampo(campo, linha);
          if not (temCampo(frm_importacao.cds_saldos, campo)) then
            exit;
          setLength(campos, length(campos)+1);
          TProcessos(self).carregaregistro(linha, campos[i]);
          inc(i)
        end;
      end;
      closeFile (arquivo);
      assignFile (arquivo,caminho);
      try
        reset(arquivo);
        readLn(arquivo, linha );
        if length(linha) > 0 then
          TProcessos(self).processaLinhaSaldo(linha, campos);
        while not Eof(arquivo) do
        begin
          readLn(arquivo,linha);
          TProcessos(self).processaLinhaSaldo(linha, campos);
        end;
      finally
        closeFile (arquivo);
      end;
    except
      closeFile (arquivo);
    end;
  end
  else  if (((UpperCase(copy(ExtractFileName(caminho),1,2))='NE')) or 
((UpperCase(copy(ExtractFileName(caminho),1,2))='NF'))) then //Notas de Empenho
        begin
          assignFile (arquivo,copy(caminho,1, length(caminho)- 4) +'.ref');
          try
            reset( arquivo );
            readLn( arquivo, linha );
            if length(linha) > 0 then
            begin
              i := 0;
              setLength(campos, length(campos)+1);
              TProcessos(self).carregaregistro(linha, campos[i]);
              inc(i);
              TProcessos(self).acertaCampo(campo, linha);
              if not (temCampo(frm_importacao.cds_empenhos, campo)) then
                exit;
              while not Eof(arquivo) do
              begin
                readLn(arquivo,linha);
                acertaCampo(campo, linha);
                if not (temCampo(frm_importacao.cds_empenhos, campo)) then
                  exit;
                setLength(campos, length(campos)+1);
                TProcessos(self).carregaregistro(linha, campos[i]);
                inc(i)
              end;
            end;
            closeFile (arquivo);
            assignFile (arquivo,caminho);
            try
              reset(arquivo);
              readLn(arquivo, linha );
              if length(linha) > 0 then
                TProcessos(self).processaLinhaEmpenho(linha, campos );
              while not Eof(arquivo) do
              begin
                readLn(arquivo,linha);
                TProcessos(self).processaLinhaEmpenho(linha, campos);
              end;
            finally
              closeFile (arquivo);
            end;
          except
            closeFile (arquivo);
          end;
        end;
end;

procedure TProcessos.processaLinhaSaldo(const linha :String; Camp :Array of 
registro );
var ultimo, i :word;
begin
  ultimo := 1;
        Write ( fSaldos, '<ROW RowState="4" ');
  for i := 0  to (length(camp)-1) do
  begin
    if frm_importacao.cds_saldos.fieldbyname(camp[i].nome).DataType = ftString  
then
    begin
      Write ( fSaldos,' '+acertaNomeCampo(camp[i].nome)+'="'+copy(linha, 
ultimo, camp[i].tamanho)+'"');
      ultimo := ultimo + camp[i].tamanho;
    end
    else
    begin
      Write ( fSaldos,' '+acertaNomeCampo(camp[i].nome)+'="'+copy(linha, 
ultimo, camp[i].precisao-camp[i].tamanho)+'.'+copy(linha, 
ultimo+camp[i].precisao-camp[i].tamanho,camp[i].tamanho )+'"');
      ultimo := ultimo + camp[i].precisao;
    end;
  end;
  Write ( fSaldos, '/>');
  writeln(fSaldos);
end;

procedure TProcessos.processaLinhaEmpenho(const linha :String; Camp :Array of 
registro);
var ultimo :word;
begin
  ultimo := 1;
        Write ( fEmpenhos, '<ROW RowState="4" ');
  Write ( fEmpenhos,' GR-UG-GESTAO-AN-NUMERO-NEUQ="'+copy(linha, ultimo, 
camp[0].tamanho)+'"');
  ultimo := ultimo + camp[0].tamanho;
  Write ( fEmpenhos,' IT-DA-EMISSAO="'+copy(linha, ultimo, 
camp[1].tamanho)+'"');
  ultimo := ultimo + camp[1].tamanho;
  Write ( fEmpenhos,' IT-IN-FAVORECIDO="'+copy(linha, ultimo, 
camp[2].tamanho)+'"');
  ultimo := ultimo + camp[2].tamanho;
  Write ( fEmpenhos,' IT-CO-FAVORECIDO="'+copy(linha, ultimo, 
camp[3].tamanho)+'"');
  ultimo := ultimo + camp[3].tamanho;
  Write ( fEmpenhos,' GR-CODIGO-EVENTO="'+copy(linha, ultimo, 
camp[4].tamanho)+'"');
  ultimo := ultimo + camp[4].tamanho;
  Write ( fEmpenhos,' IT-CO-PROGRAMA-TRABALHO-RESUMID="'+copy(linha, ultimo, 
camp[5].tamanho)+'"');
  ultimo := ultimo + camp[5].tamanho;
  Write ( fEmpenhos,' GR-FONTE-RECURSO="'+copy(linha, ultimo, 
camp[6].tamanho)+'"');
  ultimo := ultimo + camp[6].tamanho;
  Write ( fEmpenhos,' GR-NATUREZA-DESPESA="'+copy(linha, ultimo, 
camp[7].tamanho)+'"');
  ultimo := ultimo + camp[7].tamanho;
  Write ( fEmpenhos,' IT-VA-TRANSACAO="'+copy(linha, ultimo, 
camp[8].precisao-camp[8].tamanho)+','+copy(linha, 
ultimo+camp[8].precisao-camp[8].tamanho,camp[8].tamanho )+'"');
  Write ( fEmpenhos, ' />');
  writeln(fEmpenhos);
end;

procedure Tfrm_importacao.btn_novoClick(Sender: TObject);
begin
  inherited;
  Processos := TProcessos.Create;
end;

procedure Tfrm_importacao.FormClose(Sender: TObject;
  var Action: TCloseAction);
begin
  inherited;
  frm_importacao := nil;
end;

{ TProcessos }
procedure TProcessos.atualizar(const i: word);
begin
  frm_importacao.gau_analise.Progress := i+1;
  frm_importacao.gau_analise.Repaint;
end;

constructor TProcessos.Create;
begin
  inherited Create(true);
  TProcessos(self).Priority := tpNormal ;
  frm_importacao.btn_novo.enabled := false;
  frm_importacao.pan_cabecalho.Enabled := false;
  frm_importacao.gau_analise.MaxValue := frm_importacao.arquivos.Count;
  frm_importacao.gau_analise.Progress := 0;
  TProcessos(self).suspended := false;
end;

procedure TProcessos.Execute;
var i :word;
begin
  inherited;
  frm_importacao.cds_saldos.close;
  frm_importacao.cds_empenhos.close;
  if fileexists(ExtractFilePath(Application.ExeName)+'dbsaldos.xml') then
     deletefile(ExtractFilePath(Application.ExeName)+'dbsaldos.xml');
  if fileexists(ExtractFilePath(Application.ExeName)+'dbempenhos.xml') then
     deletefile(ExtractFilePath(Application.ExeName)+'dbempenhos.xml');
  AssignFile ( fSaldos, ExtractFilePath(Application.ExeName)+'dbsaldos.xml' );
  Rewrite ( fSaldos );
  writeln(fSaldos,'<?xml version="1.0" standalone="yes"?>');
  writeln(fSaldos,'<DATAPACKET Version="2.0">');
  writeln(fSaldos,'     <METADATA>');
  writeln(fSaldos,'             <FIELDS>');
  writeln(fSaldos,'                     <FIELD                                  
    attrname="IT-CO-UNIDADE-GESTORA"         fieldtype="string" required="true" 
WIDTH="6"/>');
  writeln(fSaldos,'                     <FIELD                                  
    attrname="IT-CO-GESTAO"                  fieldtype="string" required="true" 
WIDTH="5"/>');
  writeln(fSaldos,'                     <FIELD                                  
    attrname="GR-CODIGO-CONTA"               fieldtype="string" required="true" 
WIDTH="9"/>');
  writeln(fSaldos,'                     <FIELD                                  
    attrname="IT-CO-CONTA-CORRENTE-CONTABIL" fieldtype="string" required="true" 
WIDTH="43"/>');
  writeln(fSaldos,'                     <FIELD                                  
    attrname="IT-VA-DEBITO-INICIAL"          fieldtype="fixedFMT" DECIMALS="2" 
WIDTH="18"/>');
  writeln(fSaldos,'                     <FIELD                                  
    attrname="IT-VA-CREDITO-INICIAL"         fieldtype="fixedFMT" DECIMALS="2" 
WIDTH="18"/>');
  writeln(fSaldos,'                     <FIELD 
fieldname="IT-VA-DEBITO-MENSAL(1)"   attrname="IT-VA-DEBITO-MENSAL_1_"        
fieldtype="fixedFMT" DECIMALS="2" WIDTH="32"/>');
  writeln(fSaldos,'                     <FIELD 
fieldname="IT-VA-CREDITO-MENSAL(1)"  attrname="IT-VA-CREDITO-MENSAL_1_"       
fieldtype="fixedFMT" DECIMALS="2" WIDTH="32"/>');
  writeln(fSaldos,'                     <FIELD 
fieldname="IT-VA-DEBITO-MENSAL(2)"   attrname="IT-VA-DEBITO-MENSAL_2_"        
fieldtype="fixedFMT" DECIMALS="2" WIDTH="32"/>');
  writeln(fSaldos,'                     <FIELD 
fieldname="IT-VA-CREDITO-MENSAL(2)"  attrname="IT-VA-CREDITO-MENSAL_2_"       
fieldtype="fixedFMT" DECIMALS="2" WIDTH="32"/>');
  writeln(fSaldos,'                     <FIELD 
fieldname="IT-VA-DEBITO-MENSAL(3)"   attrname="IT-VA-DEBITO-MENSAL_3_"        
fieldtype="fixedFMT" DECIMALS="2" WIDTH="32"/>');
  writeln(fSaldos,'                     <FIELD 
fieldname="IT-VA-CREDITO-MENSAL(3)"  attrname="IT-VA-CREDITO-MENSAL_3_"       
fieldtype="fixedFMT" DECIMALS="2" WIDTH="32"/>');
  writeln(fSaldos,'                     <FIELD 
fieldname="IT-VA-DEBITO-MENSAL(4)"   attrname="IT-VA-DEBITO-MENSAL_4_"        
fieldtype="fixedFMT" DECIMALS="2" WIDTH="32"/>');
  writeln(fSaldos,'                     <FIELD 
fieldname="IT-VA-CREDITO-MENSAL(4)"  attrname="IT-VA-CREDITO-MENSAL_4_"       
fieldtype="fixedFMT" DECIMALS="2" WIDTH="32"/>');
  writeln(fSaldos,'                     <FIELD 
fieldname="IT-VA-DEBITO-MENSAL(5)"   attrname="IT-VA-DEBITO-MENSAL_5_"        
fieldtype="fixedFMT" DECIMALS="2" WIDTH="32"/>');
  writeln(fSaldos,'                     <FIELD 
fieldname="IT-VA-CREDITO-MENSAL(5)"  attrname="IT-VA-CREDITO-MENSAL_5_"       
fieldtype="fixedFMT" DECIMALS="2" WIDTH="32"/>');
  writeln(fSaldos,'                     <FIELD 
fieldname="IT-VA-DEBITO-MENSAL(6)"   attrname="IT-VA-DEBITO-MENSAL_6_"        
fieldtype="fixedFMT" DECIMALS="2" WIDTH="32"/>');
  writeln(fSaldos,'                     <FIELD 
fieldname="IT-VA-CREDITO-MENSAL(6)"  attrname="IT-VA-CREDITO-MENSAL_6_"       
fieldtype="fixedFMT" DECIMALS="2" WIDTH="32"/>');
  writeln(fSaldos,'                     <FIELD 
fieldname="IT-VA-DEBITO-MENSAL(7)"   attrname="IT-VA-DEBITO-MENSAL_7_"        
fieldtype="fixedFMT" DECIMALS="2" WIDTH="32"/>');
  writeln(fSaldos,'                     <FIELD 
fieldname="IT-VA-CREDITO-MENSAL(7)"  attrname="IT-VA-CREDITO-MENSAL_7_"       
fieldtype="fixedFMT" DECIMALS="2" WIDTH="32"/>');
  writeln(fSaldos,'                     <FIELD 
fieldname="IT-VA-DEBITO-MENSAL(8)"   attrname="IT-VA-DEBITO-MENSAL_8_"        
fieldtype="fixedFMT" DECIMALS="2" WIDTH="32"/>');
  writeln(fSaldos,'                     <FIELD 
fieldname="IT-VA-CREDITO-MENSAL(8)"  attrname="IT-VA-CREDITO-MENSAL_8_"       
fieldtype="fixedFMT" DECIMALS="2" WIDTH="32"/>');
  writeln(fSaldos,'                     <FIELD 
fieldname="IT-VA-DEBITO-MENSAL(9)"   attrname="IT-VA-DEBITO-MENSAL_9_"        
fieldtype="fixedFMT" DECIMALS="2" WIDTH="32"/>');
  writeln(fSaldos,'                     <FIELD 
fieldname="IT-VA-CREDITO-MENSAL(9)"  attrname="IT-VA-CREDITO-MENSAL_9_"       
fieldtype="fixedFMT" DECIMALS="2" WIDTH="32"/>');
  writeln(fSaldos,'                     <FIELD 
fieldname="IT-VA-DEBITO-MENSAL(10)"  attrname="IT-VA-DEBITO-MENSAL_10_"       
fieldtype="fixedFMT" DECIMALS="2" WIDTH="32"/>');
  writeln(fSaldos,'                     <FIELD 
fieldname="IT-VA-CREDITO-MENSAL(10)" attrname="IT-VA-CREDITO-MENSAL_10_"      
fieldtype="fixedFMT" DECIMALS="2" WIDTH="32"/>');
  writeln(fSaldos,'                     <FIELD 
fieldname="IT-VA-DEBITO-MENSAL(11)"  attrname="IT-VA-DEBITO-MENSAL_11_"       
fieldtype="fixedFMT" DECIMALS="2" WIDTH="32"/>');
  writeln(fSaldos,'                     <FIELD 
fieldname="IT-VA-CREDITO-MENSAL(11)" attrname="IT-VA-CREDITO-MENSAL_11_"      
fieldtype="fixedFMT" DECIMALS="2" WIDTH="32"/>');
  writeln(fSaldos,'                     <FIELD 
fieldname="IT-VA-DEBITO-MENSAL(12)"  attrname="IT-VA-DEBITO-MENSAL_12_"       
fieldtype="fixedFMT" DECIMALS="2" WIDTH="32"/>');
  writeln(fSaldos,'                     <FIELD 
fieldname="IT-VA-CREDITO-MENSAL(12)" attrname="IT-VA-CREDITO-MENSAL_12_"      
fieldtype="fixedFMT" DECIMALS="2" WIDTH="32"/>');
  writeln(fSaldos,'             </FIELDS>');
  writeln(fSaldos,'     </METADATA>');
  writeln(fSaldos,'     <ROWDATA>');
  AssignFile ( fEmpenhos, ExtractFilePath(Application.ExeName)+'dbempenhos.xml' 
);
  Rewrite ( fEmpenhos );
  writeln(fEmpenhos,'<?xml version="1.0" standalone="yes"?>');
  writeln(fEmpenhos,'<DATAPACKET Version="2.0">');
  writeln(fEmpenhos,'   <METADATA>');
  writeln(fEmpenhos,'           <FIELDS>');
  writeln(fEmpenhos,'                   <FIELD 
attrname="GR-UG-GESTAO-AN-NUMERO-NEUQ" fieldtype="string" WIDTH="23"/>');
  writeln(fEmpenhos,'                   <FIELD attrname="IT-DA-EMISSAO" 
fieldtype="string" WIDTH="8"/>');
  writeln(fEmpenhos,'                   <FIELD attrname="IT-IN-FAVORECIDO" 
fieldtype="string" WIDTH="1"/>');
  writeln(fEmpenhos,'                   <FIELD attrname="IT-CO-FAVORECIDO" 
fieldtype="string" WIDTH="14"/>');
  writeln(fEmpenhos,'                   <FIELD attrname="GR-CODIGO-EVENTO" 
fieldtype="string" WIDTH="6"/>');
  writeln(fEmpenhos,'                   <FIELD 
attrname="IT-CO-PROGRAMA-TRABALHO-RESUMID" fieldtype="string" WIDTH="6"/>');
  writeln(fEmpenhos,'                   <FIELD attrname="GR-FONTE-RECURSO" 
fieldtype="string" WIDTH="10"/>');
  writeln(fEmpenhos,'                   <FIELD attrname="GR-NATUREZA-DESPESA" 
fieldtype="string" WIDTH="6"/>');
  writeln(fEmpenhos,'                   <FIELD attrname="IT-VA-TRANSACAO" 
fieldtype="fixedFMT" DECIMALS="2" WIDTH="17"/>');
  writeln(fEmpenhos,'           </FIELDS>');
  writeln(fEmpenhos,'   </METADATA>');
  writeln(fEmpenhos,'   <ROWDATA>');
  for i := 0 to frm_importacao.arquivos.Count-1 do
  begin
    TProcessos(self).atualizar(i);
    TProcessos(self).analisarDados(frm_importacao.arquivos.Strings[i]);
    if frm_importacao.mm_advertencias.Lines.Count > 0 then
    begin
      closefile(fSaldos);
      exit;
    end
  end;
  writeln(fSaldos,'     </ROWDATA>');
  writeln(fSaldos,'</DATAPACKET>');
  writeln(fEmpenhos,'   </ROWDATA>');
  writeln(fEmpenhos,'</DATAPACKET>');
  closefile(fSaldos);
  closefile(fEmpenhos);
  frm_importacao.gau_analise.Visible := false;
  frm_importacao.lbl_analise.Caption := 'Finalizando análise';
  frm_importacao.lbl_analise.Visible := true;
  frm_importacao.lbl_analise.Caption := 'Análise concluída';
  frm_importacao.pan_cabecalho.Enabled := true;
  terminate;
end;

procedure Tfrm_importacao.FormShow(Sender: TObject);
begin
  inherited;
  cb_exercicio.ItemIndex := cb_exercicio.Items.IndexOf(inttostr(YearOf(now())));
end;

function TProcessos.acertaNomeCampo(const campo: String) :String;
var tmp :string;
    i :byte;
    x :word;
begin
  tmp := '';
  if (pos('(', campo) > 0) or (pos(')', campo) > 0) then
  Begin
    if (pos('(', campo) > 0) then
      x := pos('(', campo)
    else
      x := pos(')', campo);
    tmp := copy(campo, 1, x-1);
    for i := x to length(campo) do
    begin
      if (copy(campo, i, 1) = '(') or(copy(campo, i, 1) =  ')') then
        tmp := tmp +'_'
      else
        tmp := tmp +copy(campo, i, 1);
    end;
  end
  else
    tmp := campo;
  acertaNomeCampo := tmp;
end;

{ TImportaSaldo }
procedure TImportaSaldo.atualiza;
begin
  TImportaSaldo(self).Progresso.Progress := TClientDataSet(CDS).RecNo;
  TImportaSaldo(self).progresso.Repaint;
end;

constructor TImportaSaldo.Create(const cdsSaldo: Pointer);
begin
  inherited create(true);
  CDS := cdsSaldo;
  Priority := tpNormal  ;
  progresso := TGauge.Create(frm_importacao.gb_regsaldos);
  progresso.Parent := frm_importacao.gb_regsaldos;
  progresso.MaxValue := TClientDataSet(CDS).RecordCount;
  progresso.Height := 20;
  progresso.align := alBottom;
  ADOC_Saldo := TADOConnection.Create(nil);
  ADOC_Saldo.LoginPrompt := false;
  ADOC_Saldo.KeepConnection := false;
  ADOC_Saldo.CommandTimeout := 90;  
  ADOC_Saldo.Provider := 'SQLOLEDB.1';
  ADOC_Saldo.ConnectionString := DM.ADOC.ConnectionString;
  ADOC_Saldo.Connected := true;
  suspended := false;
end;

procedure TImportaSaldo.Execute;
var comando :ansistring;
  i :word;
begin
  inherited;
  try
    if not ADOC_Saldo.InTransaction then
    begin
      try
        ADOC_Saldo.BeginTrans;
        TClientDataSet(TImportaSaldo(self).CDS).First;
        While not TClientDataSet(CDS).Eof do
        begin
          comando :=
                      ' begin '+
                      '   update TMP_SOF_SALDO_CONTABIL set '+
                      '                             VL_DEBITO_INICIAL =         
  '+ Copy('00000000000000000'+ 
CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-DEBITO-INICIAL'    
).asCurrency*100), 
Length(CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-DEBITO-INICIAL'    
).asCurrency*100)), 18)+', '+
                      '                             VL_CREDITO_INICIAL =        
  '+ Copy('00000000000000000'+ 
CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-CREDITO-INICIAL'   
).asCurrency*100), 
Length(CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-CREDITO-INICIAL'   
).asCurrency*100)), 18)+', '+
                      '                             VL_DEBITO_MES_1 =           
  '+ Copy('00000000000000000'+ 
CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-DEBITO-MENSAL(1)'  
).asCurrency*100), 
Length(CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-DEBITO-MENSAL(1)'  
).asCurrency*100)), 18)+', '+
                      '                             VL_CREDITO_MES_1 =          
  '+ Copy('00000000000000000'+ 
CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-CREDITO-MENSAL(1)' 
).asCurrency*100), 
Length(CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-CREDITO-MENSAL(1)' 
).asCurrency*100)), 18)+', '+
                      '                             VL_DEBITO_MES_2 =           
  '+ Copy('00000000000000000'+ 
CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-DEBITO-MENSAL(2)'  
).asCurrency*100), 
Length(CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-DEBITO-MENSAL(2)'  
).asCurrency*100)), 18)+', '+
                      '                             VL_CREDITO_MES_2 =          
  '+ Copy('00000000000000000'+ 
CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-CREDITO-MENSAL(2)' 
).asCurrency*100), 
Length(CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-CREDITO-MENSAL(2)' 
).asCurrency*100)), 18)+', '+
                      '                             VL_DEBITO_MES_3 =           
  '+ Copy('00000000000000000'+ 
CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-DEBITO-MENSAL(3)'  
).asCurrency*100), 
Length(CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-DEBITO-MENSAL(3)'  
).asCurrency*100)), 18)+', '+
                      '                             VL_CREDITO_MES_3 =          
  '+ Copy('00000000000000000'+ 
CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-CREDITO-MENSAL(3)' 
).asCurrency*100), 
Length(CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-CREDITO-MENSAL(3)' 
).asCurrency*100)), 18)+', '+
                      '                             VL_DEBITO_MES_4 =           
  '+ Copy('00000000000000000'+ 
CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-DEBITO-MENSAL(4)'  
).asCurrency*100), 
Length(CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-DEBITO-MENSAL(4)'  
).asCurrency*100)), 18)+', '+
                      '                             VL_CREDITO_MES_4 =          
  '+ Copy('00000000000000000'+ 
CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-CREDITO-MENSAL(4)' 
).asCurrency*100), 
Length(CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-CREDITO-MENSAL(4)' 
).asCurrency*100)), 18)+', '+
                      '                             VL_DEBITO_MES_5 =           
  '+ Copy('00000000000000000'+ 
CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-DEBITO-MENSAL(5)'  
).asCurrency*100), 
Length(CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-DEBITO-MENSAL(5)'  
).asCurrency*100)), 18)+', '+
                      '                             VL_CREDITO_MES_5 =          
  '+ Copy('00000000000000000'+ 
CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-CREDITO-MENSAL(5)' 
).asCurrency*100), 
Length(CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-CREDITO-MENSAL(5)' 
).asCurrency*100)), 18)+', '+
                      '                             VL_DEBITO_MES_6 =           
  '+ Copy('00000000000000000'+ 
CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-DEBITO-MENSAL(6)'  
).asCurrency*100), 
Length(CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-DEBITO-MENSAL(6)'  
).asCurrency*100)), 18)+', '+
                      '                             VL_CREDITO_MES_6 =          
  '+ Copy('00000000000000000'+ 
CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-CREDITO-MENSAL(6)' 
).asCurrency*100), 
Length(CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-CREDITO-MENSAL(6)' 
).asCurrency*100)), 18)+', '+
                      '                             VL_DEBITO_MES_7 =           
  '+ Copy('00000000000000000'+ 
CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-DEBITO-MENSAL(7)'  
).asCurrency*100), 
Length(CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-DEBITO-MENSAL(7)'  
).asCurrency*100)), 18)+', '+
                      '                             VL_CREDITO_MES_7 =          
  '+ Copy('00000000000000000'+ 
CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-CREDITO-MENSAL(7)' 
).asCurrency*100), 
Length(CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-CREDITO-MENSAL(7)' 
).asCurrency*100)), 18)+', '+
                      '                             VL_DEBITO_MES_8 =           
  '+ Copy('00000000000000000'+ 
CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-DEBITO-MENSAL(8)'  
).asCurrency*100), 
Length(CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-DEBITO-MENSAL(8)'  
).asCurrency*100)), 18)+', '+
                      '                             VL_CREDITO_MES_8 =          
  '+ Copy('00000000000000000'+ 
CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-CREDITO-MENSAL(8)' 
).asCurrency*100), 
Length(CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-CREDITO-MENSAL(8)' 
).asCurrency*100)), 18)+', '+
                      '                             VL_DEBITO_MES_9 =           
  '+ Copy('00000000000000000'+ 
CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-DEBITO-MENSAL(9)'  
).asCurrency*100), 
Length(CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-DEBITO-MENSAL(9)'  
).asCurrency*100)), 18)+', '+
                      '                             VL_CREDITO_MES_9 =          
  '+ Copy('00000000000000000'+ 
CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-CREDITO-MENSAL(9)' 
).asCurrency*100), 
Length(CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-CREDITO-MENSAL(9)' 
).asCurrency*100)), 18)+', '+
                      '                             VL_DEBITO_MES_10 =          
  '+ Copy('00000000000000000'+ 
CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-DEBITO-MENSAL(10)' 
).asCurrency*100), 
Length(CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-DEBITO-MENSAL(10)' 
).asCurrency*100)), 18)+', '+
                      '                             VL_CREDITO_MES_10 =         
  '+ Copy('00000000000000000'+ 
CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-CREDITO-MENSAL(10)').asCurrency*100),
 
Length(CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-CREDITO-MENSAL(10)').asCurrency*100)),
 18)+', '+
                      '                             VL_DEBITO_MES_11 =          
  '+ Copy('00000000000000000'+ 
CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-DEBITO-MENSAL(11)' 
).asCurrency*100), 
Length(CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-DEBITO-MENSAL(11)' 
).asCurrency*100)), 18)+', '+
                      '                             VL_CREDITO_MES_11 =         
  '+ Copy('00000000000000000'+ 
CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-CREDITO-MENSAL(11)').asCurrency*100),
 
Length(CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-CREDITO-MENSAL(11)').asCurrency*100)),
 18)+', '+
                      '                             VL_DEBITO_MES_12 =          
  '+ Copy('00000000000000000'+ 
CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-DEBITO-MENSAL(12)' 
).asCurrency*100), 
Length(CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-DEBITO-MENSAL(12)' 
).asCurrency*100)), 18)+', '+
                      '                             VL_CREDITO_MES_12 =         
  '+ Copy('00000000000000000'+ 
CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-CREDITO-MENSAL(12)').asCurrency*100),
 
Length(CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-CREDITO-MENSAL(12)').asCurrency*100)),
 18)+
                      '                      where CO_GESTAO                 = 
'+QuotedStr(TClientDataSet(CDS).fieldbyname('IT-CO-GESTAO').AsString)+
                      '                      and   CO_UNIDADE_GESTORA        = 
'+QuotedStr(TClientDataSet(CDS).fieldbyname('IT-CO-UNIDADE-GESTORA').AsString)+
                      '                      and   CO_CONTA                  = 
'+QuotedStr(TClientDataSet(CDS).fieldbyname('GR-CODIGO-CONTA').AsString)+
                      '                      and   CO_CONTA_CORRENTE_CONTABIL= 
'+QuotedStr(TClientDataSet(CDS).fieldbyname('IT-CO-CONTA-CORRENTE-CONTABIL').AsString)+
                      '   if @@ROWCOUNT = 0 '+
                      '       INSERT INTO TMP_SOF_SALDO_CONTABIL ( CO_GESTAO, 
CO_UNIDADE_GESTORA, CO_CONTA, CO_CONTA_CORRENTE, '+
                      '                     CO_CONTA_CORRENTE_CONTABIL, 
VL_DEBITO_INICIAL, VL_CREDITO_INICIAL, VL_DEBITO_MES_1, VL_CREDITO_MES_1, '+
                      '                     VL_DEBITO_MES_2, VL_CREDITO_MES_2, 
VL_DEBITO_MES_3, VL_CREDITO_MES_3, VL_DEBITO_MES_4, VL_CREDITO_MES_4, '+
                      '                     VL_DEBITO_MES_5, VL_CREDITO_MES_5, 
VL_DEBITO_MES_6, VL_CREDITO_MES_6, VL_DEBITO_MES_7, VL_CREDITO_MES_7, '+
                      '                     VL_DEBITO_MES_8, VL_CREDITO_MES_8, 
VL_DEBITO_MES_9, VL_CREDITO_MES_9, VL_DEBITO_MES_10,VL_CREDITO_MES_10,'+
                      '                     
VL_DEBITO_MES_11,VL_CREDITO_MES_11,VL_DEBITO_MES_12,VL_CREDITO_MES_12) VALUES ( 
'+
                                                  
QuotedStr(TClientDataSet(CDS).fieldbyname('IT-CO-GESTAO').AsString)+', '+
                                                  
QuotedStr(TClientDataSet(CDS).fieldbyname('IT-CO-UNIDADE-GESTORA').AsString)+', 
'+
                                                  
QuotedStr(TClientDataSet(CDS).fieldbyname('GR-CODIGO-CONTA').AsString)+', '+
                                                  
QuotedStr(TClientDataSet(CDS).fieldbyname('IT-CO-CONTA-CORRENTE-CONTABIL').AsString)+',
 '+
                                                  
QuotedStr(TClientDataSet(CDS).fieldbyname('IT-CO-CONTA-CORRENTE-CONTABIL').AsString)+',
 '+
                                                  Copy('00000000000000000'+ 
CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-DEBITO-INICIAL'    
).asCurrency*100), 
Length(CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-DEBITO-INICIAL'    
).asCurrency*100)), 18)+', '+
                                                  Copy('00000000000000000'+ 
CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-CREDITO-INICIAL'   
).asCurrency*100), 
Length(CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-CREDITO-INICIAL'   
).asCurrency*100)), 18)+', '+
                                                  Copy('00000000000000000'+ 
CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-DEBITO-MENSAL(1)'  
).asCurrency*100), 
Length(CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-DEBITO-MENSAL(1)'  
).asCurrency*100)), 18)+', '+
                                                  Copy('00000000000000000'+ 
CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-CREDITO-MENSAL(1)' 
).asCurrency*100), 
Length(CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-CREDITO-MENSAL(1)' 
).asCurrency*100)), 18)+', '+
                                                  Copy('00000000000000000'+ 
CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-DEBITO-MENSAL(2)'  
).asCurrency*100), 
Length(CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-DEBITO-MENSAL(2)'  
).asCurrency*100)), 18)+', '+
                                                  Copy('00000000000000000'+ 
CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-CREDITO-MENSAL(2)' 
).asCurrency*100), 
Length(CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-CREDITO-MENSAL(2)' 
).asCurrency*100)), 18)+', '+
                                                  Copy('00000000000000000'+ 
CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-DEBITO-MENSAL(3)'  
).asCurrency*100), 
Length(CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-DEBITO-MENSAL(3)'  
).asCurrency*100)), 18)+', '+
                                                  Copy('00000000000000000'+ 
CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-CREDITO-MENSAL(3)' 
).asCurrency*100), 
Length(CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-CREDITO-MENSAL(3)' 
).asCurrency*100)), 18)+', '+
                                                  Copy('00000000000000000'+ 
CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-DEBITO-MENSAL(4)'  
).asCurrency*100), 
Length(CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-DEBITO-MENSAL(4)'  
).asCurrency*100)), 18)+', '+
                                                  Copy('00000000000000000'+ 
CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-CREDITO-MENSAL(4)' 
).asCurrency*100), 
Length(CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-CREDITO-MENSAL(4)' 
).asCurrency*100)), 18)+', '+
                                                  Copy('00000000000000000'+ 
CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-DEBITO-MENSAL(5)'  
).asCurrency*100), 
Length(CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-DEBITO-MENSAL(5)'  
).asCurrency*100)), 18)+', '+
                                                  Copy('00000000000000000'+ 
CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-CREDITO-MENSAL(5)' 
).asCurrency*100), 
Length(CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-CREDITO-MENSAL(5)' 
).asCurrency*100)), 18)+', '+
                                                  Copy('00000000000000000'+ 
CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-DEBITO-MENSAL(6)'  
).asCurrency*100), 
Length(CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-DEBITO-MENSAL(6)'  
).asCurrency*100)), 18)+', '+
                                                  Copy('00000000000000000'+ 
CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-CREDITO-MENSAL(6)' 
).asCurrency*100), 
Length(CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-CREDITO-MENSAL(6)' 
).asCurrency*100)), 18)+', '+
                                                  Copy('00000000000000000'+ 
CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-DEBITO-MENSAL(7)'  
).asCurrency*100), 
Length(CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-DEBITO-MENSAL(7)'  
).asCurrency*100)), 18)+', '+
                                                  Copy('00000000000000000'+ 
CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-CREDITO-MENSAL(7)' 
).asCurrency*100), 
Length(CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-CREDITO-MENSAL(7)' 
).asCurrency*100)), 18)+', '+
                                                  Copy('00000000000000000'+ 
CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-DEBITO-MENSAL(8)'  
).asCurrency*100), 
Length(CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-DEBITO-MENSAL(8)'  
).asCurrency*100)), 18)+', '+
                                                  Copy('00000000000000000'+ 
CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-CREDITO-MENSAL(8)' 
).asCurrency*100), 
Length(CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-CREDITO-MENSAL(8)' 
).asCurrency*100)), 18)+', '+
                                                  Copy('00000000000000000'+ 
CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-DEBITO-MENSAL(9)'  
).asCurrency*100), 
Length(CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-DEBITO-MENSAL(9)'  
).asCurrency*100)), 18)+', '+
                                                  Copy('00000000000000000'+ 
CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-CREDITO-MENSAL(9)' 
).asCurrency*100), 
Length(CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-CREDITO-MENSAL(9)' 
).asCurrency*100)), 18)+', '+
                                                  Copy('00000000000000000'+ 
CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-DEBITO-MENSAL(10)' 
).asCurrency*100), 
Length(CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-DEBITO-MENSAL(10)' 
).asCurrency*100)), 18)+', '+
                                                  Copy('00000000000000000'+ 
CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-CREDITO-MENSAL(10)').asCurrency*100),
 
Length(CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-CREDITO-MENSAL(10)').asCurrency*100)),
 18)+', '+
                                                  Copy('00000000000000000'+ 
CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-DEBITO-MENSAL(11)' 
).asCurrency*100), 
Length(CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-DEBITO-MENSAL(11)' 
).asCurrency*100)), 18)+', '+
                                                  Copy('00000000000000000'+ 
CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-CREDITO-MENSAL(11)').asCurrency*100),
 
Length(CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-CREDITO-MENSAL(11)').asCurrency*100)),
 18)+', '+
                                                  Copy('00000000000000000'+ 
CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-DEBITO-MENSAL(12)' 
).asCurrency*100), 
Length(CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-DEBITO-MENSAL(12)' 
).asCurrency*100)), 18)+', '+
                                                  Copy('00000000000000000'+ 
CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-CREDITO-MENSAL(12)').asCurrency*100),
 
Length(CurrToStr(TClientDataSet(CDS).fieldbyname('IT-VA-CREDITO-MENSAL(12)').asCurrency*100)),
 18)+
                      '                        )  '+
                      ' end ';
          ADOC_Saldo.Execute(comando, registrosAfetadosS, [eoExecuteNoRecords]);
          Synchronize(TImportaSaldo(self).atualiza);
          TClientDataSet(CDS).next;
        end;
        ADOC_Saldo.CommitTrans;
      except
        ADOC_Saldo.RollbackTrans;
        frm_importacao.mm_advertencias.Lines.Add('problemas na importação dos 
dados de saldos contábeis, registro '+IntToStr(TClientDataSet(CDS).recno));
      end;
    end;
  finally
    if ADOC_Saldo.Errors.Count > 0 then
      for i:= 0 to ADOC_Saldo.Errors.Count do
      begin
        if (pos('TB_SOF_UNIDADE_GESTORA', 
ADOC_Saldo.Errors.Item[i].Description)>0) then
          frm_importacao.mm_advertencias.Lines.Add('Existem Unidades Gestoras 
inexistentes na base do SIOF. Atualize as Unidades Gestoras so SIOF e importe 
novamente.')
        else  if (pos('TB_SOF_PLANO_CONTAS', 
ADOC_Saldo.Errors.Item[i].Description)>0) then
                frm_importacao.mm_advertencias.Lines.Add('Plano de contas 
desatualizado. Atualize o plano de contas do SIOF e importe novamente')
              else  if (pos('TB_SOF_GESTAO', 
ADOC_Saldo.Errors.Item[i].Description)>0) then
                      frm_importacao.mm_advertencias.Lines.Add('Cadastro de 
Gestão do SIOF está desatualizado. Atualize as Gestões e importe novamente')
                    else
                      
frm_importacao.mm_advertencias.Lines.Add(ADOC_Saldo.Errors.Item[i].Description);
      end;
    freeandnil(ADOC_Saldo);
    freeandnil(TImportaSaldo(self).progresso);
    Terminate;
  end;
end;

procedure Tfrm_importacao.btn_excluirClick(Sender: TObject);
var regsAfet :integer;
begin
  inherited;
  if not(btn_novo.enabled) then
    if (frm_importacao.mm_advertencias.Lines.Count <= 0 ) then
    begin
      frm_importacao.lbl_analise.caption := 'Carregando dados';
      frm_importacao.lbl_analise.repaint;
      frm_importacao.cds_saldos.Open;
      frm_importacao.cds_empenhos.Open;
      frm_importacao.lbl_analise.caption := 'Importando..';
      frm_importacao.lbl_analise.repaint;
      btn_excluir.Enabled := false;
      try
        if not dm.ADOC.InTransaction then
        begin
          try
            dm.ADOC.BeginTrans;
            dm.ADOC.Execute('TRUNCATE TABLE TMP_SOF_EMPENHO_AUX_IMPORTACAO', 
regsAfet,[eoExecuteNoRecords]);
            dm.ADOC.CommitTrans;
          except
            mm_advertencias.Lines.Add(dm.ADOC.Errors.Item[0].Description);
            dm.ADOC.RollbackTrans;
          end;
          TFinalizaImportacao.Create(TImportaSaldo.Create(Pointer(cds_saldos)), 
TImportaEmpenho.Create(Pointer(cds_empenhos)), dataAtualizacao);
        end;
      except
        btn_excluir.Enabled := true;
        pan_cabecalho.Enabled := true;
      end;
    end
    else
      showmessage('Existem advertências, os dados não poderão ser importados');
end;

procedure Tfrm_importacao.btn_salvarClick(Sender: TObject);
begin
  inherited;
  if not btn_excluir.Enabled then
  begin
    btn_procurar.Enabled := true;
    btn_novo.Enabled := true;
    btn_excluir.Enabled := true;
  end;
end;

{ TImportaEmpenho }
procedure TImportaEmpenho.atualiza;
begin
  ProgressoEmp.Progress := TClientDataSet(CDSEmp).RecNo;
  ProgressoEmp.Repaint;
end;

constructor TImportaEmpenho.Create(const cdsEmpenho :Pointer);
begin
  inherited create(true);
  TImportaEmpenho(self).CDSEmp := cdsEmpenho;
  TImportaEmpenho(self).Priority := tpNormal    ;
  ProgressoEmp := TGauge.Create(frm_importacao.gb_regempenhos);
  ProgressoEmp.Parent := frm_importacao.gb_regempenhos;
  ProgressoEmp.MaxValue := TClientDataSet(CDSEmp).RecordCount;
  ProgressoEmp.Height := 20;
  ProgressoEmp.align := alBottom;
  ADOC_Empenho := TADOConnection.Create(nil);
  ADOC_Empenho.LoginPrompt := false;
  ADOC_Empenho.KeepConnection := false;
  ADOC_Empenho.CommandTimeout := 90;
  ADOC_Empenho.Provider := 'SQLOLEDB.1';
  ADOC_Empenho.ConnectionString := DM.ADOC.ConnectionString;
  ADOC_Empenho.Connected := true;
  suspended := false;
end;

procedure TImportaEmpenho.Execute;
var comando :String;
    i :word;
begin
  inherited;
  try
    if not ADOC_Empenho.InTransaction then
    begin
      try
        ADOC_Empenho.BeginTrans;
        TClientDataSet(CDSEmp).First;
        While not TClientDataSet(CDSEmp).Eof do
        begin
          comando := ( ' INSERT INTO TMP_SOF_EMPENHO_AUX_IMPORTACAO  
(GR_UG_GESTAO_AN_NUMERO_NEUQ, '+
                                           'IT_DA_EMISSAO, IT_IN_FAVORECIDO, 
IT_CO_FAVORECIDO, GR_CODIGO_EVENTO, '+
                                           'IT_CO_PROGRAMA_TRABALHO_RESUMIDO, 
GR_FONTE_RECURSO, GR_NATUREZA_DESPESA, '+
                                           'IT_VA_TRANSACAO) VALUES ('+
                        
QuotedStr(TClientDataSet(CDSEmp).fieldbyname('GR-UG-GESTAO-AN-NUMERO-NEUQ').AsString)+',
 '+
                        
QuotedStr(TClientDataSet(CDSEmp).fieldbyname('IT-DA-EMISSAO').AsString)+', '+
                        
QuotedStr(TClientDataSet(CDSEmp).fieldbyname('IT-IN-FAVORECIDO').AsString)+', '+
                        
QuotedStr(TClientDataSet(CDSEmp).fieldbyname('IT-CO-FAVORECIDO').AsString)+', '+
                        
QuotedStr(TClientDataSet(CDSEmp).fieldbyname('GR-CODIGO-EVENTO').AsString)+', '+
                        
QuotedStr(TClientDataSet(CDSEmp).fieldbyname('IT-CO-PROGRAMA-TRABALHO-RESUMID').AsString)+',
 '+
                        
QuotedStr(TClientDataSet(CDSEmp).fieldbyname('GR-FONTE-RECURSO').AsString)+', '+
                        
TClientDataSet(CDSEmp).fieldbyname('GR-NATUREZA-DESPESA').AsString+', '+
                        Copy('00000000000000000'+ 
CurrToStr(TClientDataSet(CDSEmp).fieldbyname('IT-VA-TRANSACAO').value*100),
                             
Length(CurrToStr(TClientDataSet(CDSEmp).fieldbyname('IT-VA-TRANSACAO').value*100)),
 18)+
                        ') ');
          ADOC_Empenho.Execute(comando,registrosAfetadosE,[eoExecuteNoRecords]);
          Synchronize(atualiza);
          TClientDataSet(CDSEmp).next;
        end;
        ADOC_Empenho.CommitTrans;
        ADOC_Empenho.BeginTrans;
        comando := (  ' INSERT INTO TB_SOF_EMPENHO '+
                      ' SELECT  '+
                      ' 
TMP_SOF_EMPENHO_AUX_IMPORTACAO.GR_UG_GESTAO_AN_NUMERO_NEUQ, '+
                      ' TMP_SOF_EMPENHO_AUX_IMPORTACAO.IT_DA_EMISSAO, '+
                      ' TMP_SOF_EMPENHO_AUX_IMPORTACAO.IT_IN_FAVORECIDO, '+
                      ' TMP_SOF_EMPENHO_AUX_IMPORTACAO.IT_CO_FAVORECIDO, '+
                      ' TMP_SOF_EMPENHO_AUX_IMPORTACAO.GR_CODIGO_EVENTO, '+
                      ' 
TMP_SOF_EMPENHO_AUX_IMPORTACAO.IT_CO_PROGRAMA_TRABALHO_RESUMIDO, '+
                      ' TMP_SOF_EMPENHO_AUX_IMPORTACAO.GR_FONTE_RECURSO, '+
                      ' TMP_SOF_EMPENHO_AUX_IMPORTACAO.GR_NATUREZA_DESPESA, '+
                      ' TMP_SOF_EMPENHO_AUX_IMPORTACAO.IT_VA_TRANSACAO, '+
                      ' 
SUBSTRING(TMP_SOF_EMPENHO_AUX_IMPORTACAO.GR_UG_GESTAO_AN_NUMERO_NEUQ,7,5), '+
                      ' 
SUBSTRING(TMP_SOF_EMPENHO_AUX_IMPORTACAO.GR_UG_GESTAO_AN_NUMERO_NEUQ,1,6),  '+
                      ' 
SUBSTRING(TMP_SOF_EMPENHO_AUX_IMPORTACAO.GR_UG_GESTAO_AN_NUMERO_NEUQ,12,12) '+
                      ' FROM TMP_SOF_EMPENHO_AUX_IMPORTACAO LEFT OUTER JOIN '+
                      ' TB_SOF_EMPENHO ON '+
                      ' TB_SOF_EMPENHO.GR_UG_GESTAO_AN_NUMERO_NEUQ = '+
                      ' 
TMP_SOF_EMPENHO_AUX_IMPORTACAO.GR_UG_GESTAO_AN_NUMERO_NEUQ '+
                      ' WHERE TB_SOF_EMPENHO.GR_UG_GESTAO_AN_NUMERO_NEUQ IS 
NULL '
                   );
        ADOC_Empenho.Execute(comando,registrosAfetadosE,[eoExecuteNoRecords]);
        ADOC_Empenho.CommitTrans;
      except
        ADOC_Empenho.RollbackTrans;
        frm_importacao.mm_advertencias.Lines.Add('problemas na importação dos 
dados de empenho, registro '+IntToStr(TClientDataSet(CDSEmp).recno));
      end;
    end;
  finally
    if ADOC_Empenho.Errors.Count > 0 then
      for i:= 0 to ADOC_Empenho.Errors.Count do
        
frm_importacao.mm_advertencias.Lines.Add(ADOC_Empenho.Errors.Item[i].Description);

    freeandnil(ADOC_Empenho);
    freeandnil(progressoEmp);
    Terminate;
  end;
end;

{ TFinalizaImportacao }

constructor TFinalizaImportacao.Create(const sOk, eOk: Pointer; const data 
:TDateTime);
begin
  inherited create(true);
  Priority := tpNormal  ;
  saOk := sOk;
  emOk := eOk;
  dataAtualiz := data;
  ADOC_Finaliza := TADOConnection.Create(nil);
  ADOC_Finaliza.LoginPrompt := false;
  ADOC_Finaliza.KeepConnection := false;
  ADOC_Finaliza.CommandTimeout := 90;
  ADOC_Finaliza.Provider := 'SQLOLEDB.1';
  ADOC_Finaliza.ConnectionString := DM.ADOC.ConnectionString;
  ADOC_Finaliza.Connected := true;
  ADOC_Finaliza.CommandTimeout := 9000;
  frm_importacao.gau_analise.visible := false;
  suspended := false;
end;

procedure TFinalizaImportacao.atualizaLabel;
begin
  frm_importacao.lbl_analise.caption := texto;
  frm_importacao.gb_analise.Repaint;
end;

procedure TFinalizaImportacao.Execute;
var regsAfet :integer;
begin
  inherited;
  texto := 'Importando saldos contábeis e notas de empenho';
  Synchronize(atualizaLabel);
  while not(TImportaEmpenho(emOk).Terminated) or 
not(TImportaSaldo(saOk).terminated) do
    sleep(10000);
  texto := 'Reestruturando SIOF. Aguarde, poderá demorar vários minutos.';
  frm_importacao.cds_saldos.close;
  frm_importacao.cds_empenhos.close;
  Synchronize(atualizaLabel);
  try
    ADOC_Finaliza.BeginTrans;
    ADOC_Finaliza.Execute(' begin                                               
                   '+
                          '   declare @CO_TAREFA varchar(20),                   
                         '+
                          '           @CO_PROCESSAMENTO int,                    
                         '+
                          '           @NU_CPF_USUARIO varchar(14),              
                         '+
                          '           @DS_USERNAME varchar(30)                  
                         '+
                          '                                                     
                         '+
                          '   select @NU_CPF_USUARIO = 
'+QuotedStr(dm.usuarioCPF)+'                      '+
                          '   select @DS_USERNAME  = 
'+QuotedStr(dm.usuarioNome)+'                       '+
                          '   select @CO_TAREFA = ''ATUEXEC''                   
                         '+
                          '                                                     
                         '+
                          '   EXEC SP_SOF_ATUALIZA_EXECUCAO_APLICATIVO          
                         '+
                          '   @CO_TAREFA,                                       
                         '+
                          '   @NU_CPF_USUARIO,                                  
                         '+
                          '   @DS_USERNAME                                      
                         '+
                          ' end                                                 
                         '
                          , regsAfet,[eoExecuteNoRecords]
                           );

    ADOC_Finaliza.Execute('   EXEC SP_SOF_ATUALIZA_TABELAS_RESUMO_APLICATIVO    
                         '+
                          '   UPDATE TB_SOF_DATA_REFERENCIA set DT_REFERENCIA = 
convert(datetime,'+formatdatetime('MM/DD/YYYY', dataAtualiz)+') '
                          , regsAfet,[eoExecuteNoRecords]);
    
    ADOC_Finaliza.CommitTrans;
    texto := 'Importação concluída com sucesso';
    Synchronize(atualizaLabel);
    showmessage('Importação comcluída com sucesso');
  except
    
frm_importacao.mm_advertencias.Lines.Add(ADOC_Finaliza.Errors.Item[0].Description);
    ADOC_Finaliza.RollbackTrans;
    texto := 'Importação não foi concluída com sucesso, verifique as 
advertências';
    Synchronize(atualizaLabel);
    showmessage('Importação não pode ser concluída');
  end;
  freeandnil(ADOC_Finaliza);
  frm_importacao.btn_excluir.Enabled := true;
  frm_importacao.btn_procurar.Enabled := true;
  frm_importacao.btn_novo.Enabled := true;
  frm_importacao.pan_cabecalho.Enabled := true;
end;

end.



-- 
<<<<< FAVOR REMOVER ESTA PARTE AO RESPONDER ESTA MENSAGEM >>>>>

Para ver as mensagens antigas, acesse:
 http://br.groups.yahoo.com/group/delphi-br/messages

Para falar com o moderador, envie um e-mail para:
 [EMAIL PROTECTED] ou [EMAIL PROTECTED]
 
Links do Yahoo! Grupos

<*> Para visitar o site do seu grupo na web, acesse:
    http://br.groups.yahoo.com/group/delphi-br/

<*> Para sair deste grupo, envie um e-mail para:
    [EMAIL PROTECTED]

<*> O uso que você faz do Yahoo! Grupos está sujeito aos:
    http://br.yahoo.com/info/utos.html

 


Responder a