聲明部分 
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格式..將數(shù)據(jù)轉(zhuǎn)換為excel.
//速度非常快,而且具有分欄功能
//避免了用comobj帶來到弊端
//GroupCount:用于設(shè)定分欄數(shù)。。默認(rèn)為1
//ShowCompleteBoX:boolean;來設(shè)定完成是否顯示完成提示
//-------------------------------------------------------------------------------
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;//記錄數(shù)
  iFieldCount:integer;//字段數(shù)
  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 //字段數(shù)
      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);
      //---------------------------------
     (*寫入記錄,按分欄數(shù)來寫*)
     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 //分欄數(shù)
        begin
           if DataSet.Eof then break;
           inc(i);
           for K:=0 to iFieldCount-1 do //字段數(shù)
           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的轉(zhuǎn)換!','完成提示:',mb_ok+MB_IconInformation)
 finally
   closeFile(ExcelFile);
 end;
end;
新聞熱點
疑難解答