delphi7 打开excel 5
要读取Excel数据,用opendialog打开一个已经存在的Excel文件,把数据导入到oleContainer里面显示出来。请帮帮忙,谢谢!跪求!请给出代码,谢谢!...
要读取Excel数据,用opendialog打开一个已经存在的Excel文件,把数据导入到oleContainer里面显示出来。请帮帮忙,谢谢!跪求!请给出代码,谢谢!
展开
展开全部
拿Excel 2010做例子:
首先,需要在最上面的uses 里面 加上comObj
//AXLSFile 表示文件路径
procedure Xls_To_StringGrid(AXLSFile: string);
const
xlCellTypeLastCell = $0000000B;
var
XLApp, Sheet: OLEVariant;
RangeMatrix: Variant;
x, y, k, r: Integer;
vLen : integer;
begin
XLApp := CreateOleObject('Excel.Application');
try
// Hide Excel
XLApp.Visible := False;
// Open the Workbook
XLApp.Workbooks.Open(AXLSFile);
Sheet := XLApp.Workbooks[ExtractFileName(AXLSFile)].WorkSheets[1];
// In order to know the dimension of the WorkSheet, i.e the number of rows
// and the number of columns, we activate the last non-empty cell of it
Sheet.Cells.SpecialCells(xlCellTypeLastCell, EmptyParam).Activate;
// Get the value of the last row
x := XLApp.ActiveCell.Row;
// Get the value of the last column
y := XLApp.ActiveCell.Column;
// Assign the Variant associated with the WorkSheet to the Delphi Variant
RangeMatrix := XLApp.Range['A1', XLApp.Cells.Item[X, Y]].Value;
// Define the loop for filling in the TMOStringGrid
//假设是导入到表格中, 2开头表示忽略第一行表头
for k := 2 to x do
begin
eGrid.Cells[1, k - 1] := RangeMatrix[k, 1]; //Excel中第一行第一列都是从1 开始
end;
// Unassign the Delphi Variant Matrix
RangeMatrix := Unassigned;
finally
// Quit Excel
if not VarIsEmpty(XLApp) then
begin
// XLApp.DisplayAlerts := False;
XLApp.Quit;
XLAPP := Unassigned;
Sheet := Unassigned;
end;
end;
end;
首先,需要在最上面的uses 里面 加上comObj
//AXLSFile 表示文件路径
procedure Xls_To_StringGrid(AXLSFile: string);
const
xlCellTypeLastCell = $0000000B;
var
XLApp, Sheet: OLEVariant;
RangeMatrix: Variant;
x, y, k, r: Integer;
vLen : integer;
begin
XLApp := CreateOleObject('Excel.Application');
try
// Hide Excel
XLApp.Visible := False;
// Open the Workbook
XLApp.Workbooks.Open(AXLSFile);
Sheet := XLApp.Workbooks[ExtractFileName(AXLSFile)].WorkSheets[1];
// In order to know the dimension of the WorkSheet, i.e the number of rows
// and the number of columns, we activate the last non-empty cell of it
Sheet.Cells.SpecialCells(xlCellTypeLastCell, EmptyParam).Activate;
// Get the value of the last row
x := XLApp.ActiveCell.Row;
// Get the value of the last column
y := XLApp.ActiveCell.Column;
// Assign the Variant associated with the WorkSheet to the Delphi Variant
RangeMatrix := XLApp.Range['A1', XLApp.Cells.Item[X, Y]].Value;
// Define the loop for filling in the TMOStringGrid
//假设是导入到表格中, 2开头表示忽略第一行表头
for k := 2 to x do
begin
eGrid.Cells[1, k - 1] := RangeMatrix[k, 1]; //Excel中第一行第一列都是从1 开始
end;
// Unassign the Delphi Variant Matrix
RangeMatrix := Unassigned;
finally
// Quit Excel
if not VarIsEmpty(XLApp) then
begin
// XLApp.DisplayAlerts := False;
XLApp.Quit;
XLAPP := Unassigned;
Sheet := Unassigned;
end;
end;
end;
本回答被网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询