我写的采用csv格式将数据转换为excel的函数,带有分栏功能

类别:Delphi 点击:0 评论:0 推荐:

声明部分
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;

本文地址:http://com.8s8s.com/it/it5102.htm