criando um filtro usando delphi 7, excel e interbase
07/01/2010
0
Olá pessoal.
Estou enviando esta, para ver se vcs podem me dar uma luz no fim do tunel.
é que tenho de criar uma espécie de filtro para jogar registros contidos numa planilha do excel em uma tabela do interbase. é que na empresa onde trabalho temos um arquivo de associados, dos quais alguns são aposentados e pensionistas e pagam suas mensalidades via desconto bancário. O arquivo dispobilizado pela nossa confederação é no formato excel e nossa aplicação usa banco de dados interbase.
o que tenho de fazer é usando o arquivo excel, dar a situação do associado como aposentado e informar o nº do benefício, e a espécie.
vcs poderiam me orientar????
Me ajudem pessoal, pois apesar de usar o delphi não sou programador profissional.
Desde já muitissimo obrigado pela ajuda....
Estou enviando esta, para ver se vcs podem me dar uma luz no fim do tunel.
é que tenho de criar uma espécie de filtro para jogar registros contidos numa planilha do excel em uma tabela do interbase. é que na empresa onde trabalho temos um arquivo de associados, dos quais alguns são aposentados e pensionistas e pagam suas mensalidades via desconto bancário. O arquivo dispobilizado pela nossa confederação é no formato excel e nossa aplicação usa banco de dados interbase.
o que tenho de fazer é usando o arquivo excel, dar a situação do associado como aposentado e informar o nº do benefício, e a espécie.
vcs poderiam me orientar????
Me ajudem pessoal, pois apesar de usar o delphi não sou programador profissional.
Desde já muitissimo obrigado pela ajuda....
Marcos Morais
Curtir tópico
+ 0
Responder
Posts
07/01/2010
Pjrm1470
Este meu exemplo importa para um ClientDataSet (CDS), portanto a estrutura fica toda no CDS. Você so precisará estudar os campos que o excel tem para fazer um procedimento que inclua os dados do CDS para o seu interbase.
Código:
Obs: cdsTest é um TClientDataSet.
Uses
ComObj;
function ImportaExcel: Boolean;
const
XLCELL_TYPE_LAST_CELL = $0000000B;
var
xlAPP: OleVariant;
Sheet: OleVariant;
RangeMatrix: Variant;
X: Integer; // linha
Y: Integer; // coluna
K: Integer; // Linha do grid
R: Integer; // coluna do grid
I: Integer; // indice da array de fields
boC: Boolean;
begin
Result := False;
boC := False;
I := 0;
//cria Excel - Ole Object
xlAPP := CreateOleObject('Excel.Application'); try
try
xlAPP.Visible := False; // esconde o excel
xlAPP.Workbooks.Open(edtTest.Text); // abre o workbook Sheet := xlAPP.Workbooks['SeuArquivoExcel'].WorkSheets[1];
Sheet.Cells.SpecialCells(XLCELL_TYPE_LAST_CELL, EmptyParam).Activate; X := xlAPP.ActiveCell.Row; // Pega a quantidade de linhas
Y := xlAPP.ActiveCell.Column; // Pega a quantidade de colunas // Associa a variant WorkSheet com a variant do delphi
RangeMatrix := xlAPP.Range['A1', xlAPP.Cells.Item[X, y]].Value;
K := 1;
repeat // Loop para listar os registros no ClientDataSet
for R := 1 to Y do
{ grid.cells[(R-1), (K-1)] := RangeMatrix(K, R) }
if (K = 1) then
begin //define os campos
SetLength(newField, Y); // Define quantas colunas (Fields) vai ter
{##########################################}
{## DA PARA CONSTRUIR OS FIELDS PARA QUE ##}
{## TENHAM OS NOMES DE SEUS RESPECTIVOS ##}
{## CAMPO QUE ESTÃO NA PLANILHA EXCEL ##}
{##########################################}
newField[I] := TStringField.Create(Self); newField[I].FieldName := 'Field' + IntToStr(cdsTest.FieldCount);
newField[I].Name := cdsTest.Name + newField[I].FieldName;
newField[I].Index := cdsTest.FieldCount;
newField[I].DataSet := cdsTest;
Inc(I);
//cdsTest.Fields.Fields[R-1].DataType := [ftString];
end else
begin
if (boC = False) then
begin
cdsTest.CreateDataSet;
cdsTest.FieldDefs.Update;
boC := not boC;
end; if not (dtsTest.State in [dsInsert]) then
cdsTest.Insert;
cdsTest.Fields.Fields[R-1].Value := RangeMatrix[K, R];
end;
Inc(K, 1);
if (dtsTest.State in [dsInsert]) then
cdsTest.Post;
until (K > X);
RangeMatrix := Unassigned;
finally
// fecha o Excel
if not VarIsEmpty(xlAPP) then
begin
xlAPP.Quit;
xlAPP := Unassigned;
Sheet := Unassigned;
cdsTest.Open; Result := True;
end;
end;
except
on E: Exception do
ShowMessage(E.Message);
end;
end; Espero que ajude.
const
XLCELL_TYPE_LAST_CELL = $0000000B;
var
xlAPP: OleVariant;
Sheet: OleVariant;
RangeMatrix: Variant;
X: Integer; // linha
Y: Integer; // coluna
K: Integer; // Linha do grid
R: Integer; // coluna do grid
I: Integer; // indice da array de fields
boC: Boolean;
begin
Result := False;
boC := False;
I := 0;
//cria Excel - Ole Object
xlAPP := CreateOleObject('Excel.Application'); try
try
xlAPP.Visible := False; // esconde o excel
xlAPP.Workbooks.Open(edtTest.Text); // abre o workbook Sheet := xlAPP.Workbooks['SeuArquivoExcel'].WorkSheets[1];
Sheet.Cells.SpecialCells(XLCELL_TYPE_LAST_CELL, EmptyParam).Activate; X := xlAPP.ActiveCell.Row; // Pega a quantidade de linhas
Y := xlAPP.ActiveCell.Column; // Pega a quantidade de colunas // Associa a variant WorkSheet com a variant do delphi
RangeMatrix := xlAPP.Range['A1', xlAPP.Cells.Item[X, y]].Value;
K := 1;
repeat // Loop para listar os registros no ClientDataSet
for R := 1 to Y do
{ grid.cells[(R-1), (K-1)] := RangeMatrix(K, R) }
if (K = 1) then
begin //define os campos
SetLength(newField, Y); // Define quantas colunas (Fields) vai ter
{##########################################}
{## DA PARA CONSTRUIR OS FIELDS PARA QUE ##}
{## TENHAM OS NOMES DE SEUS RESPECTIVOS ##}
{## CAMPO QUE ESTÃO NA PLANILHA EXCEL ##}
{##########################################}
newField[I] := TStringField.Create(Self); newField[I].FieldName := 'Field' + IntToStr(cdsTest.FieldCount);
newField[I].Name := cdsTest.Name + newField[I].FieldName;
newField[I].Index := cdsTest.FieldCount;
newField[I].DataSet := cdsTest;
Inc(I);
//cdsTest.Fields.Fields[R-1].DataType := [ftString];
end else
begin
if (boC = False) then
begin
cdsTest.CreateDataSet;
cdsTest.FieldDefs.Update;
boC := not boC;
end; if not (dtsTest.State in [dsInsert]) then
cdsTest.Insert;
cdsTest.Fields.Fields[R-1].Value := RangeMatrix[K, R];
end;
Inc(K, 1);
if (dtsTest.State in [dsInsert]) then
cdsTest.Post;
until (K > X);
RangeMatrix := Unassigned;
finally
// fecha o Excel
if not VarIsEmpty(xlAPP) then
begin
xlAPP.Quit;
xlAPP := Unassigned;
Sheet := Unassigned;
cdsTest.Open; Result := True;
end;
end;
except
on E: Exception do
ShowMessage(E.Message);
end;
end; Espero que ajude.
Responder
Clique aqui para fazer login e interagir na Comunidade :)