小弟最近在研究导出excel表,我用字符串的形式做的。但在excel表中,表的格式怎么设定???
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExcelXP, OleServer, DB, ADODB, StdCtrls, GridsEh, DBGridEh,
ExtCtrls;
type
TForm1 = class(TForm)
dsAPB: TDataSource;
qryAPB: TADOQuery;
con1: TADOConnection;
Application1: TExcelApplication;
ExcelWorksheet1: TExcelWorksheet;
ExcelWorkbook1: TExcelWorkbook;
SaveDialog: TSaveDialog;
btntoExcel: TButton;
DBGridEh: TDBGridEh;
procedure btntoExcelClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.btntoExcelClick(Sender: TObject);
var
mField:String;
I,K:integer;
mxs:boolean;
begin
if qryAPB.RecordCount=0 then Exit;
if Application.MessageBox('是否把当前信息转换为Excel表格?','',mb_Yesno)<>6 then
begin
Exit;
end;
if Application.MessageBox('是否启动Excel界面?','系统提示',mb_Yesno)<>6 then
mxs:=False
else
mxs:=True;
try
Application1.Connect;
except
MessageDlg('Excel 可能未安装!',mterror,[mbok],0);
Abort;
end;
Screen.Cursor:=crHourGlass;
Application1.Workbooks.Add(null,0);
ExcelWorkbook1.ConnectTo(Application1.Workbooks[1]);
ExcelWorksheet1.ConnectTo(ExcelWorkBook1.Worksheets[1] as _Worksheet);
For I:=1 to DBGridEh.Columns.Count do
begin
ExcelWorksheet1.Cells.Item[3,I].Value:=DBGridEh.Columns[I-1].Title.Caption;
ExcelWorksheet1.Cells.Item[3,I].Borders.LineStyle :=1;
ExcelWorksheet1.Cells.Item[3,I].Font.Bold :=True;
end;
with qryAPB do
begin
DisableControls;
First;
K:=4;
{ mdim:=0; //进度条
mdim:=RecordCount;
Gauge1.MaxValue:=mdim;
mdim:=0; }
While Not Eof do
begin
For I:=1 to dbgrideh.Columns.Count do
begin
if (length(Trim(dbgrideh.Columns[I-1].FieldName))=0) then
begin
ExcelWorksheet1.Cells.Item[K,I].Value:=' ';
ExcelWorkSheet1.Cells.Item[k,I].Borders.LineStyle :=1;
end
else
begin
mfield:=dbgrideh.Columns[I-1].FieldName;
ExcelWorksheet1.Cells.Item[K,I].Value:=FieldByName(mfield).AsString;
ExcelWorkSheet1.Cells.Item[k,I].Borders.LineStyle :=1;
end;
end;
Next;
K:=K+1;
{ Inc(mdim);
Gauge1.Progress:=mdim;
Gauge1.Refresh; }
end;
with ExcelWorksheet1 do
begin
Columns.AutoFit; //自动列宽
Cells.Item[1,1]:='输入标题';
Range[Cells.Item[1,1],Cells.Item[1,I]].HorizontalAlignment:=xlCenter;
Range[Cells.Item[1,1],Cells.Item[1,I]].VerticalAlignment:=xlCenter;
Range[Cells.Item[1,1],Cells.Item[1,I]].Merge(Cells.Item[1,I]);
Cells.Item[1,I].Font.Size:='28';
end;
with ExcelWorksheet1 do //设置打印页面
begin
PageSetup.CenterHeader:='输入页眉';
PageSetup.CenterFooter:='输入页脚';
PageSetup.HeaderMargin:=1/0.035;
PageSetup.HeaderMargin:=3/0.035;
end;
EnableControls;
end;
if mxs then
begin
Application1.Visible[0]:=true;
end
else
begin
if SaveDialog.Execute then
begin
try
ExcelWorksheet1.SaveAs(SaveDialog.FileName);
Application.MessageBox('保存成功!','系统提示',mb_ok);
except
Application.MessageBox('保存失败!','系统提示',mb_ok);
end;
end;
Application1.Disconnect;
Application1.Quit;
end;
Screen.Cursor:=crDefault;
end;
end.