procedure Tmainform.SaveToExcelClick(Sender: TObject);
var
i,j,k:integer;
xls:OleVariant;
begin
//创建Excel对象, 需要在单元加上ComObj;
try
xls:=CreateOleObject('Excel.Application');
except
//showMessage(sMsgNotInstallExcel,sTitleError,1);
exit;
end;
xls.WorkBooks.add; //增加一个表
xls.Visible:=true; //可见
xls.Caption:='另存为EXCEL文件';
//以下为设置EXCEL各列的宽度
//xls.Columns[1].ColumnWidth:=5;
//表格标题为文件名称
xls.Cells(1,1):='jjjjjjjjjjjjjjj';
//画加框线范围A1:H1 1-左 2-右 3-顶 4-底 5-斜(/)6-斜(/)
//for k:=1 to 4 do
//xls.Range['A1:H1'].Borders[k].Weight:=2 ;
//xls.Cells(1,3):='0000';
xls.Cells(2,1):='数据导出日期:'+DateToStr(now);
//设置背景颜色
xls.Range['A1:G1'].Interior.ColorIndex:= 37; //37 为天蓝色
//DBGrideh1标题栏写入excel标题
for i:=1 to DBGrideh1.FieldCount do
begin
xls.Cells[3,i].Value:=DBGrideh1.Columns[i-1].Title.Caption;
xls.Cells[3,i].Interior.ColorIndex:=15;//15为灰色
for k:=1 to 4 do
xls.Cells[3,i].Borders[k].Weight:=2; //每个单元格加框线
end;
//从第4行开始循环写入DBGrideh1的数据--------------------------
i:=4 ;
with DataModule1.ADOQuery_member do
begin
first; //第一条
while not eof do //i: 控制行
begin
for j:=1 to DBGrideh1.FieldCount do //j:控制列
begin
xls.cells(i,j):=FieldByName(DBGrideh1.Columns[j-1].FieldName).AsString ;
for k:=1 to 4 do //单元格加框线
xls.Cells[i,j].Borders[k].Weight:=2 ;
end;
inc(i); //行号i递增+1
next; //while do 下一条数据
end;
end;
//保存EXCEL表格
//if not xls.ActiveWorkBook.Saved then
// xls.ActiveWorkBook.SaveAs(fn);
//SetForegroundWindow(Application.Handle); //本语句是防止软件窗体被其它窗体覆盖
//MsgBox(sMsgExportSucceed,sTitleHint,0);
//xls.quit; //退出EXCEL程序
end;