J.S*_*dio 0 delphi excel ole process delphi-xe7
我有这个代码:
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
XLApp.Visible:=False;
XLApp.Workbooks.Open(AXLSFile);
Sheet:=XLApp.Workbooks[ExtractFileName(AXLSFile)].WorkSheets[1];
Sheet.Cells.SpecialCells(xlCellTypeLastCell, EmptyParam).Activate;
x:=XLApp.ActiveCell.Row;
y:=XLApp.ActiveCell.Column;
AGrid.RowCount:=x;
AGrid.ColCount:=y;
RangeMatrix:=XLApp.Range['A1', XLApp.Cells.Item[X, Y]].Value;
k:=1;
repeat
for r:=1 to y do
AGrid.Cells[(r - 1),(k - 1)]:=RangeMatrix[K, R];
Inc(k,1);
until k > x;
RangeMatrix:=Unassigned;
Result:=True;
finally
if not VarIsEmpty(XLApp) then
begin
Sheet:=Unassigned;
XLApp.Workbooks[ExtractFileName(AXLSFile)].Close;
XLApp.Quit;
XLAPP:=Unassigned;
end;
try freeandnil(XLAPP) except; end;
try freeandnil(Sheet) except; end;
end;
end;
Run Code Online (Sandbox Code Playgroud)
但是在退出Quit命令之后,该过程仍然保留在列表中,注意事项:我执行搜索并理解如果有引用的对象它仍然在列表中,但我相信我已经全部发布了.
Excel的Quit()命令不是同步的,进程实际退出可能需要一些时间.
是的,您可能有活动的对象引用.您还没有清除RangeMatrix,如果你发生异常repeat循环,所以它可能并不清楚,直到XlsToStringGrid()退出.您应该使用多个try/finally块,每个对象一个.
请不要打电话FreeAndNil()给(Ole)Variant变量!它只适用于TObject指针.
试试这个:
function XlsToStringGrid(AGrid: TStringGrid; AXLSFile: string): Boolean;
const
xlCellTypeLastCell = $0000000B;
var
XLApp, WorkBook, Sheet: OLEVariant;
RangeMatrix: Variant;
x, y, k, r: Integer;
begin
Result := False;
XLApp := CreateOleObject('Excel.Application');
try
XLApp.Visible := False;
XLApp.Workbooks.Open(AXLSFile);
try
WorkBook := XLApp.Workbooks[ExtractFileName(AXLSFile)];
try
Sheet := WorkBook.WorkSheets[1];
try
Sheet.Cells.SpecialCells(xlCellTypeLastCell, EmptyParam).Activate;
x := XLApp.ActiveCell.Row;
y := XLApp.ActiveCell.Column;
AGrid.RowCount := x;
AGrid.ColCount := y;
RangeMatrix := XLApp.Range['A1', XLApp.Cells.Item[X, Y]].Value;
try
k := 1;
repeat
for r := 1 to y do
AGrid.Cells[(r - 1),(k - 1)] := RangeMatrix[K, R];
Inc(k);
until k > x;
finally
RangeMatrix := Unassigned;
end;
Result := True;
finally
Sheet := Unassigned;
end;
finally
WorkBook.Close;
WorkBook := Unassigned;
end;
finally
XLApp.Workbooks.Close;
end;
finally
XLApp.Quit;
XLAPP := Unassigned;
end;
end;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
833 次 |
| 最近记录: |