📄 打印查询结果到excel的delphi代码.txt
字号:
var
my:Tdbgrid;
i,j,total,rows: Integer;
temp:string;
Sheet: Variant;
num:integer;
isfind:boolean;
query:Tquery;
begin
my:=dbgrid1;
temp:='月末库存查询';
ds_1.DataSet:=TADOQuery(qry_1); //注意此处的用法
if not VarIsEmpty(XLApp) then
begin
if XLApp.Visible=false then
begin
XLApp.Visible := True;
XLAPP.WindowState := xlMaximized;
XLApp.ScreenUpdating := True;
XLApp.Workbooks.Add(xlWBatWorkSheet);
XLApp.Workbooks[1].WorkSheets[1].Name := temp;
XLApp.Workbooks[1].WorkSheets[1].activate;
Sheet := XLApp.Workbooks[1].WorkSheets[temp];
end;
if XLApp.Visible=true then
begin
num:=XLAPP.Workbooks.count;
if num=0 then //没有工作薄
begin
XLApp.Visible := True;
XLAPP.WindowState := xlMaximized;
XLApp.Workbooks.Add(xlWBatWorkSheet);
XLApp.Workbooks[1].WorkSheets[1].Name := temp;
XLApp.Workbooks[1].WorkSheets[1].activate;
Sheet := XLApp.Workbooks[1].WorkSheets[temp];
end
else if num=1 then //有工作薄
begin
num:=XLApp.Workbooks[1].WorkSheets.count;
isfind:=false;
for i:=1 to num do
begin
if XLApp.Workbooks[1].WorkSheets[i].Name= temp then
begin
XLApp.Workbooks[1].WorkSheets[i].Cells.ClearContents;
isfind:=true;
break;
end;
end;//end for
if isfind then //找到
begin
XLApp.Visible := True;
XLAPP.WindowState := xlMaximized;
XLApp.Workbooks[1].WorkSheets[temp].Activate;
Sheet := XLApp.Workbooks[1].WorkSheets[temp];
end
else //没有找到
begin
XLApp.Visible := True;
XLAPP.WindowState := xlMaximized;
XLApp.Workbooks[1].sheets.Add(XLApp.Workbooks[1].WorkSheets[1],,1,xlWorkSheet);
XLApp.Workbooks[1].WorkSheets[1].Name :=temp;
XLApp.Workbooks[1].WorkSheets[1].activate;
Sheet := XLApp.Workbooks[1].WorkSheets[temp];
end;
end;
end;
end
else //没有ole对象时创建实例
begin
XLApp:= CreateOleObject('Excel.Application');
if VarIsEmpty(XLApp) then
begin
application.MessageBox('请在打印查询结果前先安装<Excel>程序!','警告',mb_ok+mb_iconwarning);
exit;
end;
XLApp.Visible := True;
XLAPP.WindowState := xlMaximized;
XLApp.Workbooks.Add(xlWBatWorkSheet);
XLApp.Workbooks[1].WorkSheets[1].Name := temp;
Sheet := XLApp.Workbooks[1].WorkSheets[temp];
end;
//-----------填充查询结果------------------------------------
qry_1.First;
total:=(my as Tdbgrid).fieldCount;
rows:=qry_1.RecordCount;
//填充标题
for i := 0 to total - 1 do
begin
Sheet.Cells[1,i+1]:=(my as Tdbgrid).Fields[i].fieldname;
end;
//填充内容
for i:=0 to rows - 1 do
begin
for j:=0 to total - 1 do
sheet.cells[i+2,j+1]:=qry_1.Fieldbyname((my as Tdbgrid).Fields[j].fieldname).asstring;
qry_1.next;
end;
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -