Cargar un excel en un TStringGrid

El resultado final es el siguiente:

Aquí os dejo el código fuente:
uses
ComObj;
type
TForm1 = class(TForm)
StringGrid1: TStringGrid;
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
function Load_Excel_To_TStringGrid(StringGrid: TStringGrid; ExcelFile: string): Boolean;
const
xlCellTypeLastCell = $0000000B;
var
ExcelApp, Sheet: OLEVariant;
RangeSheet: Variant;
Row, Col, i, j: Integer;
begin
Result := False;
ExcelApp := CreateOleObject('Excel.Application');
try
ExcelApp.Visible := False;
ExcelApp.Workbooks.Open(ExcelFile);
Sheet := ExcelApp.Workbooks[ExtractFileName(ExcelFile)].WorkSheets[1];
Sheet.Cells.SpecialCells(xlCellTypeLastCell, EmptyParam).Activate;
Row := ExcelApp.ActiveCell.Row;
Col := ExcelApp.ActiveCell.Column;
StringGrid.RowCount := Row;
StringGrid.ColCount := Col;
RangeSheet := ExcelApp.Range['A1', ExcelApp.Cells.Item[Row, Col]].Value;
i := 1;
repeat
for j := 1 to Col do
StringGrid.Cells[(j - 1), (i - 1)] := RangeSheet[i, j];
Inc(i, 1);
StringGrid.RowCount := i + 1;
until i > Row;
RangeSheet := Unassigned;
finally
if not VarIsEmpty(ExcelApp) then
begin
ExcelApp.Save;
ExcelApp.Quit;
ExcelApp := Unassigned;
Sheet := Unassigned;
Result := True;
end;
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
if Load_Excel_To_TStringGrid(StringGrid1, ExtractFilePath(ParamStr(0)) + '\Table1.xls') then
ShowMessage('Table has been loaded!');
end;
end.
Comments
Post a Comment