Importar arquivo .csv ignorando os espaços de cada linha.
Pessoal, é a primeira vez que abro um tópico em um forum e estou com um probleminha...
Estou fazendo um aplicativo onde é necessário fazer um importação de arquivo .csv (separado por ponto-vísgulas). O código está funcionando perfeitamente, importando e gravando na tabela do Firebird. O conteúdo do arquivo .csv é o seguinte: teste.csv
Rafael;RJ;82728790
Julio;SP;82727788
Clara;BH;82772890
Raul;RJ;81622573
Fernanda;RJ;98932989
O problema é que quando em alguma linha existe um espaço em branco, por exemplo: Rafael Ricardo;RJ;82728790.
Ele pensa que o espaço entre uma palavra indica outra coluna.
Eu queria um código em que o espaço em branco fosse ignorado e aceitasse apenas o ponto vírgula como delimitador de caracter.
O código que estou usando é o seguinte:
Se alguém puder ajudar agradeço imensamente.
Desculpa pela bagunça no código, ainda não organizei.
Estou fazendo um aplicativo onde é necessário fazer um importação de arquivo .csv (separado por ponto-vísgulas). O código está funcionando perfeitamente, importando e gravando na tabela do Firebird. O conteúdo do arquivo .csv é o seguinte: teste.csv
Rafael;RJ;82728790
Julio;SP;82727788
Clara;BH;82772890
Raul;RJ;81622573
Fernanda;RJ;98932989
O problema é que quando em alguma linha existe um espaço em branco, por exemplo: Rafael Ricardo;RJ;82728790.
Ele pensa que o espaço entre uma palavra indica outra coluna.
Eu queria um código em que o espaço em branco fosse ignorado e aceitasse apenas o ponto vírgula como delimitador de caracter.
O código que estou usando é o seguinte:
procedure TFLogbook.btnImportClick(Sender: TObject);
var
Arq : TextFile;
texto : string;
I : Integer;
function MV : String;
var
Monta : String;
begin
monta := '';
inc(I);
While Texto[I] > '*' do
begin
If Texto[I]= ';' then
break;
monta := monta + Texto[I];
inc(I);
end;
result := monta;
end;
//begin
//if OpenDialog1.Execute then
begin
Screen.Cursor := crHourGlass;
DM.CDSExcel.Open;//a tabela onde quero por os dados excel
AssignFile(Arq,'C:\Documents and Settings\Rafael Ricardo\Desktop\teste.csv');
Reset(Arq);
if not EOF(Arq) then
repeat
ReadLn(Arq,Texto);
with DM.CDSExcel do begin
I := 0;
DM.CDSExcel.Insert;
DM.CDSExcelCLIENTE.AsString:= MV;// é meu campo
DM.CDSExcelCIDADE.AsString := MV;//operação outro campo
DM.CDSExcelFONE.AsInteger :=StrToInt(MV);//outro campo
DM.CDSExcelEMPRESA.AsString:= 'teste';
DM.CDSExcel.Post;
DM.CDSExcel.ApplyUpdates(0);
end;
until EOF(Arq);// ate o fim arquivo CSV
Closefile(Arq);//fecha arquivo CSV
Screen.Cursor := crDefault;
ShowMessage('Importado!');
end;
Se alguém puder ajudar agradeço imensamente.
Desculpa pela bagunça no código, ainda não organizei.
Rafael
Curtidas 0
Respostas
Tiago Silva
22/06/2010
Olá caro Rafael,
Ao meu entender...
Não está legal.
Experimente mudar sua função MV para...
Abraços !
Ao meu entender...
While Texto[I] > '*' do
Não está legal.
Experimente mudar sua função MV para...
... function MV : String; var Monta : String; nI : Integer; begin monta := ''; inc(I); nI := Length(Texto); While I <= nI do begin If Texto[I]= ';' then break; monta := monta + Texto[I]; inc(I); end; result := monta; end; ...
Abraços !
GOSTEI 0
Emerson Nascimento
22/06/2010
você não precisa criar uma função para desmembrar seu texto. é possível usar o objeto TStringList para isso.
tente assim:
procedure TFLogbook.btnImportClick(Sender: TObject);
var
Arq: TextFile;
Texto: string;
Txt: TStringList;
begin
Txt := TStringList.Create; // cria a stringlist
Txt.StrictDelimiter := True; // indica que o delimitador é somente aquele definido abaixo
Txt.Delimiter := ';'; // caractere delimitador de campos
try
Screen.Cursor := crHourGlass;
AssignFile(Arq,'C:\csv.csv');
Reset(Arq);
if not EOF(Arq) then
repeat
ReadLn(Arq, Texto);
Txt.DelimitedText := Texto; // desmembra o texto
with DM.CDSExcel do
begin
I := 0;
DM.CDSExcel.Insert;
DM.CDSExcelCLIENTE.AsString := Txt[0]; // é meu campo
DM.CDSExcelCIDADE.AsString := Txt[1]; // operação outro campo
DM.CDSExcelFONE.AsInteger := StrToInt(Txt[2]); // outro campo
DM.CDSExcelEMPRESA.AsString:= 'teste';
DM.CDSExcel.Post;
DM.CDSExcel.ApplyUpdates(0);
end;
until EOF(Arq);
finally
Closefile(Arq); //fecha arquivo CSV
Screen.Cursor := crDefault;
end;
FreeAndNil(Txt);
end;
tente assim:
procedure TFLogbook.btnImportClick(Sender: TObject);
var
Arq: TextFile;
Texto: string;
Txt: TStringList;
begin
Txt := TStringList.Create; // cria a stringlist
Txt.StrictDelimiter := True; // indica que o delimitador é somente aquele definido abaixo
Txt.Delimiter := ';'; // caractere delimitador de campos
try
Screen.Cursor := crHourGlass;
AssignFile(Arq,'C:\csv.csv');
Reset(Arq);
if not EOF(Arq) then
repeat
ReadLn(Arq, Texto);
Txt.DelimitedText := Texto; // desmembra o texto
with DM.CDSExcel do
begin
I := 0;
DM.CDSExcel.Insert;
DM.CDSExcelCLIENTE.AsString := Txt[0]; // é meu campo
DM.CDSExcelCIDADE.AsString := Txt[1]; // operação outro campo
DM.CDSExcelFONE.AsInteger := StrToInt(Txt[2]); // outro campo
DM.CDSExcelEMPRESA.AsString:= 'teste';
DM.CDSExcel.Post;
DM.CDSExcel.ApplyUpdates(0);
end;
until EOF(Arq);
finally
Closefile(Arq); //fecha arquivo CSV
Screen.Cursor := crDefault;
end;
FreeAndNil(Txt);
end;
GOSTEI 0
Rafael
22/06/2010
você não precisa criar uma função para desmembrar seu texto. é possível usar o objeto TStringList para isso.
tente assim:
procedure TFLogbook.btnImportClick(Sender: TObject);
var
Arq: TextFile;
Texto: string;
Txt: TStringList;
begin
Txt := TStringList.Create; // cria a stringlist
Txt.StrictDelimiter := True; // indica que o delimitador é somente aquele definido abaixo
Txt.Delimiter := ';'; // caractere delimitador de campos
try
Screen.Cursor := crHourGlass;
AssignFile(Arq,'C:\csv.csv');
Reset(Arq);
if not EOF(Arq) then
repeat
ReadLn(Arq, Texto);
Txt.DelimitedText := Texto; // desmembra o texto
with DM.CDSExcel do
begin
I := 0;
DM.CDSExcel.Insert;
DM.CDSExcelCLIENTE.AsString := Txt[0]; // é meu campo
DM.CDSExcelCIDADE.AsString := Txt[1]; // operação outro campo
DM.CDSExcelFONE.AsInteger := StrToInt(Txt[2]); // outro campo
DM.CDSExcelEMPRESA.AsString:= 'teste';
DM.CDSExcel.Post;
DM.CDSExcel.ApplyUpdates(0);
end;
until EOF(Arq);
finally
Closefile(Arq); //fecha arquivo CSV
Screen.Cursor := crDefault;
end;
FreeAndNil(Txt);
end;
tente assim:
procedure TFLogbook.btnImportClick(Sender: TObject);
var
Arq: TextFile;
Texto: string;
Txt: TStringList;
begin
Txt := TStringList.Create; // cria a stringlist
Txt.StrictDelimiter := True; // indica que o delimitador é somente aquele definido abaixo
Txt.Delimiter := ';'; // caractere delimitador de campos
try
Screen.Cursor := crHourGlass;
AssignFile(Arq,'C:\csv.csv');
Reset(Arq);
if not EOF(Arq) then
repeat
ReadLn(Arq, Texto);
Txt.DelimitedText := Texto; // desmembra o texto
with DM.CDSExcel do
begin
I := 0;
DM.CDSExcel.Insert;
DM.CDSExcelCLIENTE.AsString := Txt[0]; // é meu campo
DM.CDSExcelCIDADE.AsString := Txt[1]; // operação outro campo
DM.CDSExcelFONE.AsInteger := StrToInt(Txt[2]); // outro campo
DM.CDSExcelEMPRESA.AsString:= 'teste';
DM.CDSExcel.Post;
DM.CDSExcel.ApplyUpdates(0);
end;
until EOF(Arq);
finally
Closefile(Arq); //fecha arquivo CSV
Screen.Cursor := crDefault;
end;
FreeAndNil(Txt);
end;
PERFEITO EMERSON!! Mas estou com um probleminha...não consegui descobrir porquê, quando eu compilo, dá um erro na parte que destaquei em amarelo, diz que StrictDelimiter não é uma variável declarada. Estranho...não consegui achar um erro no código que causasse isso.
GOSTEI 0
Rafael
22/06/2010
Olá caro Rafael,
Ao meu entender...
Não está legal.
Experimente mudar sua função MV para...
Abraços !
Ao meu entender...
While Texto[I] > '*' do
Não está legal.
Experimente mudar sua função MV para...
... function MV : String; var Monta : String; nI : Integer; begin monta := ''; inc(I); nI := Length(Texto); While I <= nI do begin If Texto[I]= ';' then break; monta := monta + Texto[I]; inc(I); end; result := monta; end; ...
Abraços !
Ok Muito Obrigado Thiago!
GOSTEI 0
Rafael
22/06/2010
você não precisa criar uma função para desmembrar seu texto. é possível usar o objeto TStringList para isso.
tente assim:
procedure TFLogbook.btnImportClick(Sender: TObject);
var
Arq: TextFile;
Texto: string;
Txt: TStringList;
begin
Txt := TStringList.Create; // cria a stringlist
Txt.StrictDelimiter := True; // indica que o delimitador é somente aquele definido abaixo
Txt.Delimiter := ';'; // caractere delimitador de campos
try
Screen.Cursor := crHourGlass;
AssignFile(Arq,'C:\csv.csv');
Reset(Arq);
if not EOF(Arq) then
repeat
ReadLn(Arq, Texto);
Txt.DelimitedText := Texto; // desmembra o texto
with DM.CDSExcel do
begin
I := 0;
DM.CDSExcel.Insert;
DM.CDSExcelCLIENTE.AsString := Txt[0]; // é meu campo
DM.CDSExcelCIDADE.AsString := Txt[1]; // operação outro campo
DM.CDSExcelFONE.AsInteger := StrToInt(Txt[2]); // outro campo
DM.CDSExcelEMPRESA.AsString:= 'teste';
DM.CDSExcel.Post;
DM.CDSExcel.ApplyUpdates(0);
end;
until EOF(Arq);
finally
Closefile(Arq); //fecha arquivo CSV
Screen.Cursor := crDefault;
end;
FreeAndNil(Txt);
end;
tente assim:
procedure TFLogbook.btnImportClick(Sender: TObject);
var
Arq: TextFile;
Texto: string;
Txt: TStringList;
begin
Txt := TStringList.Create; // cria a stringlist
Txt.StrictDelimiter := True; // indica que o delimitador é somente aquele definido abaixo
Txt.Delimiter := ';'; // caractere delimitador de campos
try
Screen.Cursor := crHourGlass;
AssignFile(Arq,'C:\csv.csv');
Reset(Arq);
if not EOF(Arq) then
repeat
ReadLn(Arq, Texto);
Txt.DelimitedText := Texto; // desmembra o texto
with DM.CDSExcel do
begin
I := 0;
DM.CDSExcel.Insert;
DM.CDSExcelCLIENTE.AsString := Txt[0]; // é meu campo
DM.CDSExcelCIDADE.AsString := Txt[1]; // operação outro campo
DM.CDSExcelFONE.AsInteger := StrToInt(Txt[2]); // outro campo
DM.CDSExcelEMPRESA.AsString:= 'teste';
DM.CDSExcel.Post;
DM.CDSExcel.ApplyUpdates(0);
end;
until EOF(Arq);
finally
Closefile(Arq); //fecha arquivo CSV
Screen.Cursor := crDefault;
end;
FreeAndNil(Txt);
end;
PERFEITO EMERSON!! Mas estou com um probleminha...não consegui descobrir porquê, quando eu compilo, dá um erro na parte que destaquei em amarelo, diz que StrictDelimiter não é uma variável declarada. Estranho...não consegui achar um erro no código que causasse isso.
Alguém consegue entender porque o compilador informa que StrictDelimiter é uma variável não declarada?
GOSTEI 0
João Sobrinho
22/06/2010
Qual a versão do seu Delphi ?
Acredito que StrictDelimiter seja a partir do Delphi 2006.
GOSTEI 0
Rafael
22/06/2010
Qual a versão do seu Delphi ?
Acredito que StrictDelimiter seja a partir do Delphi 2006.
Na Mosca João!!, pelo que acabei de pesquisar na net, a versão do meu Delphi, que é 7, não suporta StrictDelimiter.
Vi algumas pessoas falando que eu tinha que usar "ExtractStrings", mas eu não tenho a menor idéia de como adaptar isso ao código, o pior é que já venho tentato fazer isso a quase um ano e não consigo.. : (
GOSTEI 0
João Sobrinho
22/06/2010
Colega, vê se ajuda:
http://www.jasonwhite.co.uk/30-functions-delphi-explode-function-like-php-explode/
GOSTEI 0
Emerson Nascimento
22/06/2010
altere sua função MV:
function MV: String;
var
letra: integer;
begin
Result := '';
if Pos(';', texto) > 0 then
begin
for letra := 1 to Length(texto) do
if texto[letra] <> ';' then
Result := Result + texto[letra]
else
Break;
texto := RightStr(texto, Length(texto) - Length(Result) -1);
end
else
begin
Result := texto;
texto := '';
end;
end;
para que seja possível utilizar a função RightStr(), adicione a unit StrUtils à sua cláusula uses.
function MV: String;
var
letra: integer;
begin
Result := '';
if Pos(';', texto) > 0 then
begin
for letra := 1 to Length(texto) do
if texto[letra] <> ';' then
Result := Result + texto[letra]
else
Break;
texto := RightStr(texto, Length(texto) - Length(Result) -1);
end
else
begin
Result := texto;
texto := '';
end;
end;
para que seja possível utilizar a função RightStr(), adicione a unit StrUtils à sua cláusula uses.
GOSTEI 0
Rafael
22/06/2010
Pessoal, Muito obrigado pela ajuda!!! Vocês me ajudaram muito! Já consegui fazer duncionar e espero poder ajudar em breve também outras pessoas como eu assim como vocÇes me ajudaram!!
O código que eu usei foi o seguinte:
Abracos!! Valeu mesmo!!!
O código que eu usei foi o seguinte:
procedure TFLogbook.BitBtn2Click(Sender: TObject);
var
DataFile : TextFile;
lineFile : String;
fileStrings : TStringList;
begin
OpenDialog1.Execute;
if FileExists(OpenDialog1.FileName) then //o usuário abrirá
//o arquivo com diálogo do Windows
begin
AssignFile(DataFile, OpenDialog1.Filename);
Reset(DataFile);
try
fileStrings := TStringList.Create;
try
while not EOF (DataFile) do
begin
Readln(DataFile, lineFile);
//substitua o ; pelo caractere separador do arquivo
ExtractStrings([';'],[' '],PChar(lineFile),fileStrings);
with DM.CDSExcel do Begin
Insert;
//manipula as strings extraídas, como gravar seus valores em
//uma tabela do banco de dados
DM.CDSExcelCLIENTE.AsString := fileStrings[0];
DM.CDSExcelCIDADE.AsString := fileStrings[1];
DM.CDSExcelFONE.AsInteger := StrToInt(fileStrings[2]);
//DM.CDSExcelEMPRESA.AsString := fileStrings[3];
DM.CDSExcel.Post;
DM.CDSExcel.ApplyUpdates(0);
end;
//limpa o conteúdo da TStringList criada
fileStrings.Clear;
end;
finally
fileStrings.Free;
end;
finally
CloseFile(DataFile);
end;
end;
ShowMessage('Importado!');
end;
Abracos!! Valeu mesmo!!!
GOSTEI 0