Carregando arquivo XLS
Várias pessoas já perguntaram aqui no fórum e diretamente a mim como fazer para carregar um arquivo XLS, melhor forma que particularmente encontrei é carregando primeiramente em um TStringGrid e depois então trabalhar com os valores. Abaixo segue um pequeno exemplo de aplicativo que carrega o XLS em um TStringGrid, bastando apenas chamar a função XlsToStringGrid() passando o TStringGrid e o endereço do arquivo. Esta função XlsToStringGrid encontrei na web, e aos poucos fui modificando a mesma para funcionar de forma perfeita a importação.
Arquivo .pas
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Grids, StdCtrls, Buttons, ExtCtrls, ComObj;
type
TForm1 = class(TForm)
Panel1: TPanel;
BitBtn3: TBitBtn;
Edit1: TEdit;
SpeedButton1: TSpeedButton;
OpenDialog: TOpenDialog;
stgExcel1: TStringGrid;
procedure SpeedButton1Click(Sender: TObject);
procedure BitBtn3Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
function XlsToStringGrid(AGrid: TStringGrid; AXLSFile: string): Boolean;
const
xlCellTypeLastCell = $0000000B;
var
XLApp, Sheet: OLEVariant;
RangeMatrix: Variant;
x, y, k, r: Integer;begin
Result:=False;
//Cria Excel- OLE Object
XLApp:=CreateOleObject('Excel.Application');
try
//Esconde Excel
XLApp.Visible:=False;
//Abre o Workbook
XLApp.Workbooks.Open(AXLSFile);
Sheet:=XLApp.Workbooks[ExtractFileName(AXLSFile)].WorkSheets[1];
Sheet.Cells.SpecialCells(xlCellTypeLastCell, EmptyParam).Activate;
//Pegar o número da última linha
x:=XLApp.ActiveCell.Row;
//Pegar o número da última coluna
y:=XLApp.ActiveCell.Column;
//Seta Stringgrid linha e coluna
AGrid.RowCount:=x + 1;
AGrid.ColCount:=y;
//Associaca a variant WorkSheet com a variant do Delphi
RangeMatrix:=XLApp.Range['A1', XLApp.Cells.Item[X, Y]].Value;
//Cria o loop para listar os registros no TStringGrid
k:=1;
for r:=1 to y do
AGrid.Cells[(r - 1),0]:=IntToStr(r - 1);
repeat
for r:=1 to y do
AGrid.Cells[(r - 1),(k)]:=RangeMatrix[K, R];
Inc(k,1);
until k > x;
RangeMatrix:=Unassigned;finally
//Fecha o Excel
if not VarIsEmpty(XLApp) then
begin
XLApp.Quit;
XLAPP:=Unassigned;
Sheet:=Unassigned;
Result:=True;
end;
end;
end;
procedure TForm1.SpeedButton1Click(Sender: TObject);begin
if (OpenDialog.Execute) then
Edit1.Text:=OpenDialog.FileName;
end;
procedure TForm1.BitBtn3Click(Sender: TObject);begin
XlsToStringGrid(stgExcel1,Edit1.Text)
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 Panel1: TPanel
Left = 0
Top = 0
Width = 775
Height = 41
Align = alTop
TabOrder = 0
object SpeedButton1: TSpeedButton
Left = 506
Top = 8
Width = 23
Height = 22
Caption = '...'
OnClick = SpeedButton1Click
end
object BitBtn3: TBitBtn
Left = 544
Top = 6
Width = 75
Height = 25
Caption = 'Carrega'
TabOrder = 0
OnClick = BitBtn3Click
end
object Edit1: TEdit
Left = 8
Top = 8
Width = 497
Height = 21
TabOrder = 1
Text = 'Edit1'
end
end
object stgExcel1: TStringGrid
Left = 0
Top = 41
Width = 775
Height = 472
Align = alClient
BorderStyle = bsNone
ColCount = 1
DefaultColWidth = 200
DefaultRowHeight = 18
FixedCols = 0
RowCount = 1
FixedRows = 0
TabOrder = 1
end
object OpenDialog: TOpenDialog
DefaultExt = '*.xls'
Filter = 'Arquivos Excel|*.xls'
Left = 368
Top = 8
end
end
Discussão (1)
Carregando comentários...