聲明部分
procedure DataToExcelCSV(SaveFileName:string;DataSet:TDataSet;ShowCompleteBoX:Boolean=True;GroupCount:integer=1);
......
{------------------------------------------------------}
{檢測findStr是否in mainStr,如果存在則返回True,否則False}
{------------------------------------------------------}
function TFun.IsStrInOtherStr(mainStr,FindStr: string): Bool;
begin
if strPos(pAnsiChar(mainStr),pAnsichar(FindStr))=nil
then
result:=False
else
result:=True;
end;
-------------------------------------------------------------------------------------
//lijinhao 2004-4-4
//采用csv格式..將數據轉換為Excel.
//速度非常快,而且具有分欄功能
//避免了用comobj帶來到弊端
//GroupCount:用於設定分欄數。。默認為1
//ShowCompleteBoX:boolean;來設定完成是否顯示完成提示
//-------------------------------------------------------------------------------
procedure TFun.DataToExcelCSV(SaveFileName:string;DataSet:TDataSet;ShowCompleteBoX:Boolean;GroupCount:integer);
Function CheckStr(str:string):string;
begin
if IsStrInOtherStr(str,',') then str:='"'+str+'"';
result:=str;
end;
//===============//
var
ExcelFile:TextFile;
iRecordCount:integer;//記錄數
iFIEldCount:integer;//字段數
i,j,k:integer;
TempStr:string;
begin
try
if Not DataSet.Active then DataSet.Open;
iRecordCount:=DataSet.RecordCount;
iFieldCount:=DataSet.FIEldCount;
assignFile(ExcelFile,SaveFileName+'.csv');
rewrite(ExcelFile);
DataSet.First;
(*--------寫字段頭------*)
TempStr:='';
for K:=0 to iFIEldCount-1 do //字段數
begin
if TempStr<>'' then
TempStr:=TempStr+','+CheckStr(DataSet.Fields[k].FIEldName)
else
TempStr:=CheckStr(DataSet.Fields[k].FIEldName)
end;(* for K:=1 to FIEldCount do*)
for i:= 1 to GroupCount-1 do TempStr:=TempStr+','+TempStr;
writeLn(ExcelFile,TempStr);
//---------------------------------
(*寫入記錄,按分欄數來寫*)
i:=1;
while i<=round(iRecordCount div GroupCount) do
begin
TempStr:='';
//如:F0 F1 F2 F3 | F0 F1 F2 F3
for j:=1 to GroupCount do //分欄數
begin
if DataSet.Eof then break;
inc(i);
for K:=0 to iFIEldCount-1 do //字段數
begin
//--------------
if tempstr<>'' then
TempStr:=TempStr+','+CheckStr(DataSet.FIElds[k].AsString)
else
TempStr:=CheckStr(DataSet.FIElds[k].AsString);
//------------
end;(* for K:=1 to FIEldCount do*)
DataSet.Next;
end;(* for j:=1 to GroupCount do*)
writeLn(ExcelFile,TempStr);
if DataSet.Eof then break;
end;//while i<=round(iRecordCount div GroupCount) do
if ShowCompleteBoX then MessageBox(0,'完成DataToExcel的轉換!','完成提示:',mb_ok+MB_IconInformation)
finally
closeFile(ExcelFile);
end;
end;