Ir para conteúdo

POWERED BY:

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

marcio.theis

[Resolvido] Carregando arquivo CSV

Recommended Posts

Bom, recentemente precisei efetuar importação de um arquivo CSV, entre vários componentes e fontes encontrados na web nenhum atendia completamente o que eu queria fazer, então com base nos fontes da web e solucionando problemas que eu tinha para importar, desenvolvi umas funções que fazer a importação...

Precisa somente chamar uma função de nome: ImportaArquivoCSV() passando como parâmetro o local do arquivo e o número de colunas do mesmo, sendo utilizado um TStringGrid para receber todas as informações do CSV.

 

 

 

Arquivo .pas

 

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, Grids, StdCtrls, Buttons, ExtCtrls;

type
  TForm1 = class(TForm)
	stg: TStringGrid;
	Panel1: TPanel;
	BitBtn2: TBitBtn;
	procedure BitBtn2Click(Sender: TObject);
  private
	{ Private declarations }
	function FormataCampo(campo: string; delimitador: char; coluna, linhaLista: integer; lista: TStringList; var temAspasInicial, achouAspasFinal: boolean): string;
	procedure ImportaArquivoCSV(arquivo: string; delimitador: char; numColunas: integer);
	procedure RemoveLinhaStringGrid(linha: integer);
  public
	{ Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.RemoveLinhaStringGrid(linha: integer);
var
	x, y: integer;
begin
for x:=linha to stg.RowCount - 2 do
	for y:=0 to stg.ColCount - 1 do
		stg.Cells[y,x]:=stg.Cells[y,x + 1];
stg.RowCount:=stg.RowCount - 1;
end;

function TForm1.FormataCampo(campo: string; delimitador: char; coluna, linhaLista: integer; lista: TStringList; var temAspasInicial, achouAspasFinal: boolean): string;
var
	x, aux: integer;
	str: string;
	delimitadorOK, encontrou: Boolean;
begin
if (not achouAspasFinal) then
	begin
	encontrou:=False;
	for x:=1 to Length(campo) do
		begin
		if (campo[x] = '"') then
			begin
			if (campo[x + 1] = ',') then
				begin
				encontrou:=True;
				Break;
				end;
			end;
		end;
	if (encontrou) then
		begin
		str:=copy(campo,1,x);
		achouAspasFinal:=True;
		lista[linhaLista]:=copy(lista[linhaLista],Length(str) + 2,Length(lista[linhaLista]) - Length(str));
		end
	else
		str:=campo;
	end
else
	begin
	x:=1;
	aux:=0;
	str:='';
	delimitadorOK:=False;
	while (x < Length(campo) + 1) and (aux < coluna) do
		begin
		if (campo[x] = '"') then
			delimitadorOK:=not delimitadorOK;
		if (campo[x] = delimitador) and (not delimitadorOK) then
			Inc(aux);
		Inc(x);
		end;
	delimitadorOK:=False;
	while (x < Length(campo) + 1) and ((campo[x] <> delimitador) or delimitadorOK) do
		begin
		if (campo[x] = '"') then
			begin
			temAspasInicial:=not temAspasInicial;
			achouAspasFinal:=not achouAspasFinal;
			delimitadorOK:=not delimitadorOK;
			end;
		str:=str + campo[x];
		Inc(x);
		end;
	end;
FormataCampo:=Trim(str);
end;

procedure TForm1.ImportaArquivoCSV(arquivo: string; delimitador: char; numColunas: integer);
var
	listaCSV: TStringList;
	x, xAux, numLinha, numLinhaAux: integer;
	aspasIni, aspasFim: boolean;
	strTemp: string;
begin
listaCSV:=TStringList.Create;
try
	stg.ColCount:=numColunas;
	listaCSV.LoadFromFile(arquivo);

	numLinha:=0;
	while (numLinha <= listaCSV.Count - 1) do
		begin
		stg.RowCount:=numLinha + 1;
		x:=0;
		xAux:=0;
		numLinhaAux:=numLinha;
		while (x <= stg.ColCount - 1) do
			begin
			strTemp:=FormataCampo(listaCSV[numLinha],delimitador,xAux,numLinha,listaCSV,aspasIni,aspasFim);
			if (stg.Cells[x,numLinhaAux] <> '') then
				strTemp:=stg.Cells[x,numLinhaAux] + #13#10 + strTemp;
			if (strTemp <> '') and (strTemp[1] = '"') and (strTemp[Length(strTemp)] = '"') then
				strTemp:=copy(strTemp,2,Length(strTemp) - 2);
			stg.Cells[x,numLinhaAux]:=strTemp;
			if ((aspasIni) and (not aspasFim)) then
				begin
				xAux:=-1;
				Inc(numLinha);
				end
			else
				begin
				Inc(x);
				Inc(xAux);
				aspasIni:=False;
				aspasFim:=True;
				end;
			end;
		Inc(numLinha);
		end;

	numLinha:=0;
	while (numLinha <= stg.RowCount - 1) do
		begin
		if (stg.Cells[0,numLinha] = '') then
			RemoveLinhaStringGrid(numLinha)
		else
			Inc(numLinha);
		end;

finally
	listaCSV.Free;
	end;
end;

procedure TForm1.BitBtn2Click(Sender: TObject);
begin
ImportaArquivoCSV('C:\arquivo.csv',',',21);
end;

end.

 

 

 

Arquivo .dfm

 

object Form1: TForm1
  Left = 220
  Top = 106
  Width = 783
  Height = 540
  Caption = 'Form1'
  Color = clBtnFace
  Font.Charset = DEFAULT_CHARSET
  Font.Color = clWindowText
  Font.Height = -11
  Font.Name = 'MS Sans Serif'
  Font.Style = []
  OldCreateOrder = False
  PixelsPerInch = 96
  TextHeight = 13
  object stg: TStringGrid
	Left = 0
	Top = 41
	Width = 775
	Height = 472
	Align = alClient
	ColCount = 21
	DefaultColWidth = 100
	FixedCols = 0
	RowCount = 1
	FixedRows = 0
	Options = [goFixedVertLine, goFixedHorzLine, goVertLine, goHorzLine, goRangeSelect, goEditing]
	TabOrder = 0
  end
  object Panel1: TPanel
	Left = 0
	Top = 0
	Width = 775
	Height = 41
	Align = alTop
	TabOrder = 1
	object BitBtn2: TBitBtn
	  Left = 8
	  Top = 8
	  Width = 75
	  Height = 25
	  Caption = 'Carregar'
	  TabOrder = 0
	  OnClick = BitBtn2Click
	end
  end
end

Compartilhar este post


Link para o post
Compartilhar em outros sites

×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.