我在使用delphi倒出excel方面使用的是TQueryTable控件,这个控件的作用相当于excel里面的"数据"---->"获取外部数据"---->"倒入文本文件",这种倒入方式主要思路是先把要保存的数据写到一个文本文件里面,然后使用TQueryTable将文本文件倒入到excel里面,这种方式倒入的速度是一条一条倒入的几十倍,效率非常快.
具体的实现是:
(一)把DataSet中的数据写入一个文本
function TComm.ReadyFile(Fn: string; Ds: TDataSet): Boolean;
var i,rowcount:integer;
line:string;
begin
Result:=False;
if not Ds.Active then exit;
rowcount:=Ds.FieldCount;
AssignFile(F,Fn);
try
try
ReWrite(F);
line:=Ds.Fields[0].DisplayName;
for i:=1 to rowcount-1 do line:=line+' '+Ds.Fields[i].DisplayName;//先准备好标题
Writeln(F,line);
Ds.First;//下面是一条一条的写入数据到文本文件,每行一条记录,每字段之间使用Tab间隔
while not Ds.Eof do
begin
line:=Ds.Fields[0].AsString;
for i:=1 to rowcount-1 do line:=line+' '+Ds.Fields[i].AsString;//注意,这里的' '是Tab键
Writeln(F,line);
Ds.Next;
end;
Result:=True;
except
Result:=False;
exit;
end;
finally
CloseFile(F);
end;
end;
(二)还要准备一个OleVariant参数,这个参数是一个整数变量,这个参数的目的是为了在倒入excel的时候正确区分列是文本还是数字,如果不准备这个参数,例如0000111这样的文本导入后就会成为111这样的数字.
function TComm.InitFormatA(DataSet: TDataSet): OleVariant;
var i:integer;
A:Variant;
begin
A:=VarArrayCreate([0,DataSet.Fields.Count-1],varVariant);
for i:=0 to DataSet.FieldCount-1 do
if DataSet.Fields[i].DataType=ftString then A[i]:=2 else A[i]:=1;//如果是文本,元素就是2,否则就是1
InitFormatA:=A;
end;
(三)文本准备好了,格式参数也准备好了,就可以连接excel使用ExcelQueryTable控件导入数据了.
procedure TForm1.Button1Click(Sender: TObject);
var
str:string;
i:Integer;
excelapp,sheet:Variant;
begin
// lbl2.Caption:=DateTimeToStr(Now);
str:='';
dbgrd1.DataSource.DataSet.DisableControls;
for i:=0 to dbgrd1.DataSource.DataSet.FieldCount-1 do
str:=str+dbgrd1.DataSource.DataSet.fields[i].DisplayLabel+char(9);
str:=str+#13;
dbgrd1.DataSource.DataSet.First;
while not(dbgrd1.DataSource.DataSet.eof) do begin
for i:=0 to dbgrd1.DataSource.DataSet.FieldCount-1 do
str:=str+dbgrd1.DataSource.DataSet.Fields[i].AsString+char(9);
str:=str+#13;
dbgrd1.DataSource.DataSet.next;
procedure Tfm_bmcl_priceview_edt.DbgridSaveToExcel(dbgrid:TDBgrid);
var
XlAPP:Variant;
Sheet1:Variant;
i,j:integer;
curRow:integer;
begin
if dbgrid.DataSource.DataSet.RecordCount<1 then exit;
//?建excel?象
try
XlApp:=createoleobject('Excel.Application');
XLApp.Visible:=false;
XLApp.Workbooks.Add(xlWBatWorkSheet);
Sheet1 := XLApp.Workbooks[1].WorkSheets['sheet1'];
// XLApp.Workbooks.Options.CheckSpellingAsYouType:= False;
// XLApp.Workbooks.Options.CheckGrammarAsYouType:= False;
except
on e:exception do
begin
dbgrid.DataSource.DataSet.First;
i:=2;
while not dbgrid.DataSource.DataSet.Eof do
begin
//?理一行
curRow:=0;
for j:=0 to dbgrid.Columns.Count-1 do
begin
Sheet1.Columns[j+1].NumberFormat:='@'; //////////設計某列為文本類型
Sheet1.cells[i,curRow+1]:=TRim(dbgrid.Fields[j].DisplayText) ;
inc(curRow);
end;
i:=i+1;
dbgrid.DataSource.DataSet.Next;
end;
XLApp.Visible:=true;
end;