程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> Delphi >> Delphi dbgrid 導出 excel 方法 轉載

Delphi dbgrid 導出 excel 方法 轉載

編輯:Delphi

delphi dbgrid 導出Excel表  

/////////  利用剪貼板,速度很快!適合裝有Excel的機器/////////////////////  
 
  USES  Clipbrd,ComObj;  
   
  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;  
   
          lbl1.Caption:=IntToStr(dbgrd1.DataSource.DataSet.RecNo);  
          Application.ProcessMessages;  
       
        end;//end  while  
   
        dbgrd1.DataSource.DataSet.EnableControls;  
   
        clipboard.Clear;  
        Clipboard.Open;  
        Clipboard.AsText:=str;  
        Clipboard.Close;  
        excelapp:=createoleobject('excel.application');  
        excelapp.workbooks.add(1);  //  excelapp.workbooks.add(-4167);  
        sheet:=excelapp.workbooks[1].worksheets[1];  
        sheet.name:='sheet1';  
        sheet.paste;  
        Clipboard.Clear;  
  //      sheet.columns.font.Name:='宋體';  
  //      sheet.columns.font.size:=9;  
  //      sheet.Columns.AutoFit;  
        excelapp.visible:=true;  
  //      lbl3.Caption:=DateTimeToStr(Now);  
   
  end;  
   
  /////////////////////////////////////////////



////////////利用TStringList,速度很快!適合沒有裝Excel的機器////////////////////////  
   
  procedure  TForm1.Button1Click(Sender:  TObject);  
  var  
      s:TStringList;  
      str:string;  
      i:Integer;  
  begin  
  //    lbl1.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;  
   
  //        lbl3.Caption:=IntToStr(dbgrd1.DataSource.DataSet.RecNo);  
  //        Application.ProcessMessages;  
   
        end;//end  while  
   
        dbgrd1.DataSource.DataSet.EnableControls;  
        s:=TStringList.Create;  
        s.Add(str);  
        s.SaveToFile('c:\temp.xls');//保存到c:\temp.xls  
        s.Free;  
  //      lbl2.Caption:=DateTimeToStr(Now);  
   
  end;  
 ////////////////////////////////////////////////
***********************************************************
(Delphi)Excel的快速導入
***********************************************************

(Delphi)Excel的快速導入
//怎樣可以提高EXCEL的導出速度?

uses ADODB,excel97,adoint;

function TForm1.ExportToExcel: Boolean;
var
  xlApp,xlBook,xlSheet,xlQuery: Variant;
  adoConnection,adoRecordset: Variant;
begin
  adoConnection := CreateOleObject('ADODB.Connection');
  adoRecordset := CreateOleObject('ADODB.Recordset');
  adoConnection.Open('Provider=Microsoft.Jet.OLEDB.4.0;Data Source=E:\Tree.mdb;Persist Security Info=False');
  adoRecordset.CursorLocation := adUseClient;
  adoRecordset.Open('SELECT * FROM tree',adoConnection,1,3);

  try
    xlApp := CreateOleObject('Excel.Application');
    xlBook := xlApp.Workbooks.Add;
    xlSheet := xlBook.Worksheets['sheet1'];
   
    //設置這一列為 文本列 ,讓 "00123" 正確顯示,而不是自動轉換為"123"
    xlSheet.Columns['C:C'].NumberFormatLocal := '@';

    xlApp.Visible := True;

    //把查詢結果導入EXCEL數據
    xlQuery := xlSheet.QueryTables.Add(adoRecordset,xlSheet.Range['A1']);  //關鍵是這一句
    xlQuery.FieldNames := True;
    xlQuery.RowNumbers := False;
    xlQuery.FillAdjacentFormulas := False;
    xlQuery.PreserveFormatting := True;
    xlQuery.RefreshOnFileOpen := False;
    xlQuery.BackgroundQuery := True;
    //xlQuery.RefreshStyle := xlInsertDeleteCells;
    xlQuery.SavePassword := True;
    xlQuery.SaveData := True;
    xlQuery.AdjustColumnWidth := True;
    xlQuery.RefreshPeriod := 0;
    xlQuery.PreserveColumnInfo := True;
    xlQuery.FieldNames := True;
    xlQuery.Refresh;

    xlBook.SaveAs('d:\fromD.xls',xlNormal,'','',False,False);

  finally
    if not VarIsEmpty(XLApp) then begin
      XLApp.displayAlerts:=false;
      XLApp.ScreenUpdating:=true;
      XLApp.quit;
    end;
  end;
end;






///////////////////////////////////////////////////
procedure saveToExcel();
var
   Eclapp,workbook:variant;
   i,n:integer;
begin
   if not adoquery1.Active then exit;
   if adoquery1.RecordCount<=0 then exit;

   if application.MessageBox('確認導出excel表嗎?','提示',mb_okcancel+mb_iconinformation)=idcancel then exit;
   Eclapp := createoleobject('Excel.Application');
   Eclapp.workbooks.add;
   for i:=0 to dbgrid2.FieldCount-1 do
   begin
     Eclapp.cells[1,i+1]:=dbgrid2.Columns[i].Title.Caption;
   end;
   Eclapp.cells[1,5]:='簽字';

   adoquery1.First;
   n:=2;
   while not adoquery1.Eof do
   begin
     eclapp.cells[n,1] := adoquery1.Fields[0].AsString;
     eclapp.cells[n,2] := adoquery1.Fields[1].AsString;
     eclapp.cells[n,3] := adoquery1.Fields[2].AsString;
     eclapp.cells[n,4] := adoquery1.Fields[4].AsString;
     eclapp.cells[n,6] :='         ';
     inc(n);
     adoquery1.Next;
   end;

   eclapp.cells[n,1] := '滿足條件記錄的總數為:'+inttostr(adoquery1.RecordCount)+'條';
   application.MessageBox('數據導出完成!','提示',mb_ok+mb_iconinformation);
   eclapp.visible := true;

end;


 www.lingutrans.com  杭州翻譯公司  杭州翻譯

 www.fanyi18.com   杭州翻譯

 www.fanyi8888.com   杭州翻譯

 www.51ytsoft.com   杭州教務軟件 在線學習 在線考試
 
方法二
procedure CopyDbDataToExcel(Args: array of const);  
var  
  iCount, jCount: Integer;  
  XLApp: Variant;  
  Sheet,range: Variant;  
  I: Integer;  
begin  
  Screen.Cursor := crHourGlass;  
  if not VarIsEmpty(XLApp) then  
  begin  
    XLApp.DisplayAlerts := False;  
    XLApp.Quit;  
    VarClear(XLApp);  
  end;

  try  
    XLApp:=CreateOleObject(Excel.Application);  
  except  
    Screen.Cursor := crDefault;  
    Exit;  
  end;

  XLApp.WorkBooks.Add;  
  XLApp.SheetsInNewWorkbook := High(Args) + 1;

  for I := Low(Args) to High(Args) do  
  begin  
    XLApp.WorkBooks[1].WorkSheets[I+1].Name := TDBGrid(Args[I].VObject).Name;  
    Sheet := XLApp.Workbooks[1].WorkSheets[TDBGrid(Args[I].VObject).Name];

    if not TDBGrid(Args[I].VObject).DataSource.DataSet.Active then  
    begin  
      Screen.Cursor := crDefault;  
      Exit;  
    end;  
    TDBGrid(Args[I].VObject).DataSource.DataSet.first;  
    for iCount := 0 to TDBGrid(Args[I].VObject).Columns.Count - 1 do  
    range:=sheet.range[sheet.cells[1,1],sheet.cells[1,iCount + 1]];  
    range.select;  
    range.merge;  
    sheet.cells[1,1]:=[+fqueryhuman.dbedit2.text+]+個人報銷記錄(普通報銷、特殊報銷)查詢;  
    jCount :=2;  
    for iCount := 0 to TDBGrid(Args[I].VObject).Columns.Count - 1 do  
    Sheet.Cells[2, iCount + 1]:=TDBGrid(Args[I].VObject).Columns.Items[iCount].Title.Caption;  
  while not TDBGrid(Args[I].VObject).DataSource.DataSet.Eof do  
    begin  
      for iCount := 0 to TDBGrid(Args[I].VObject).Columns.Count - 1 do  
        Sheet.Cells[jCount + 1, iCount + 1] :=  
      TDBGrid(Args[I].VObject).Columns.Items[iCount].Field.AsString;

      Inc(jCount);  
      TDBGrid(Args[I].VObject).DataSource.DataSet.Next;  
    end;  
    XlApp.Visible := True;  
  end;  
  Screen.Cursor := crDefault;  
end;


方法三


delphi導入/導出excel
2008年03月02日 星期日 16:39
從Excel文件中,導入數據到SQL數據庫中,很簡單,直接用下面的語句:

--如果接受數據導入的表已經存在
insert into 表 select * from
OPENROWSET('MICROSOFT.JET.OLEDB.4.0'
,'Excel 5.0;HDR=YES;DATABASE=c:\test.xls',sheet1$)
--如果導入數據並生成表
select * into 表 from
OPENROWSET('MICROSOFT.JET.OLEDB.4.0'
,'Excel 5.0;HDR=YES;DATABASE=c:\test.xls',sheet1$)



--如果從SQL數據庫中,導出數據到Excel,如果Excel文件已經存在,而且已經按照要接收的數據創建好表頭,就可以簡單的用:
insert into OPENROWSET('MICROSOFT.JET.OLEDB.4.0'
,'Excel 5.0;HDR=YES;DATABASE=c:\test.xls',sheet1$)
select * from 表


--如果Excel文件不存在,也可以用BCP來導成類Excel的文件,注意大小寫:
--導出表的情況
EXEC master..xp_cmdshell 'bcp 數據庫名.dbo.表名 out "c:\test.xls" /c -/S"服務器名" /U"用戶名" -P"密碼"'

--導出查詢的情況
EXEC master..xp_cmdshell 'bcp "SELECT au_fname, au_lname FROM pubs..authors ORDER BY au_lname" queryout "c:\test.xls" /c -/S"服務器名" /U"用戶名" -P"密碼"'




--下面是導出真正Excel文件的方法:

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[p_exporttb]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[p_exporttb]
GO




create proc p_exporttb
@tbname sysname,     --要導出的表名
@path nvarchar(1000),    --文件存放目錄
@fname nvarchar(250)=''   --文件名,默認為表名
as
declare @err int,@src nvarchar(255),@desc nvarchar(255),@out int
declare @obj int,@constr nvarchar(1000),@sql varchar(8000),@fdlist varchar(8000)

--參數檢測
if isnull(@fname,'')='' set @fname=@tbname+'.xls'

--檢查文件是否已經存在
if right(@path,1)<>'\' set @path=@path+'\'
create table #tb(a bit,b bit,c bit)
set @sql=@path+@fname
insert into #tb exec master..xp_fileexist @sql

--數據庫創建語句
set @sql=@path+@fname
if exists(select 1 from #tb where a=1)
set @constr='DRIVER={Microsoft Excel Driver (*.xls)};DSN='''';READONLY=FALSE'
        +';CREATE_DB="'+@sql+'";DBQ='+@sql
else
set @constr='Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties="Excel 8.0;HDR=YES'
     +';DATABASE='+@sql+'"'


--連接數據庫
exec @err=sp_oacreate 'adodb.connection',@obj out
if @err<>0 goto lberr

exec @err=sp_oamethod @obj,'open',null,@constr
if @err<>0 goto lberr



--創建表的SQL
select @sql='',@fdlist=''
select @fdlist=@fdlist+',['+a.name+']'
,@sql=@sql+',['+a.name+'] '
   +case
    when b.name like '%char'
    then case when a.length>255 then 'memo'
     else 'text('+cast(a.length as varchar)+')' end
    when b.name like '%int' or b.name='bit' then 'int'
    when b.name like '�tetime' then 'datetime'
    when b.name like '%money' then 'money'
    when b.name like '%text' then 'memo'
    else b.name end
FROM syscolumns a left join systypes b on a.xtype=b.xusertype
where b.name not in('image','uniqueidentifier','sql_variant','varbinary','binary','timestamp')
and object_id(@tbname)=id
select @sql='create table ['+@tbname
+']('+substring(@sql,2,8000)+')'
,@fdlist=substring(@fdlist,2,8000)
exec @err=sp_oamethod @obj,'execute',@out out,@sql
if @err<>0 goto lberr

exec @err=sp_oadestroy @obj

--導入數據
set @sql='openrowset(''MICROSOFT.JET.OLEDB.4.0'',''Excel 8.0;HDR=YES;IMEX=1
    ;DATABASE='+@path+@fname+''',['+@tbname+'$])'

exec('insert into '+@sql+'('+@fdlist+') select '+@fdlist+' from '+@tbname)

return

lberr:
exec sp_oageterrorinfo 0,@src out,@desc out
lbexit:
select cast(@err as varbinary(4)) as 錯誤號
   ,@src as 錯誤源,@desc as 錯誤描述
select @sql,@constr,@fdlist
go



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[p_exporttb]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[p_exporttb]
GO




create proc p_exporttb
@sqlstr varchar(8000),    --查詢語句,如果查詢語句中使用了order by ,請加上top 100 percent
@path nvarchar(1000),    --文件存放目錄
@fname nvarchar(250),    --文件名
@sheetname varchar(250)=''   --要創建的工作表名,默認為文件名
as
declare @err int,@src nvarchar(255),@desc nvarchar(255),@out int
declare @obj int,@constr nvarchar(1000),@sql varchar(8000),@fdlist varchar(8000)

--參數檢測
if isnull(@fname,'')='' set @fname='temp.xls'
if isnull(@sheetname,'')='' set @sheetname=replace(@fname,'.','#')

--檢查文件是否已經存在
if right(@path,1)<>'\' set @path=@path+'\'
create table #tb(a bit,b bit,c bit)
set @sql=@path+@fname
insert into #tb exec master..xp_fileexist @sql

--數據庫創建語句
set @sql=@path+@fname
if exists(select 1 from #tb where a=1)
set @constr='DRIVER={Microsoft Excel Driver (*.xls)};DSN='''';READONLY=FALSE'
        +';CREATE_DB="'+@sql+'";DBQ='+@sql
else
set @constr='Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties="Excel 8.0;HDR=YES'
     +';DATABASE='+@sql+'"'

--連接數據庫
exec @err=sp_oacreate 'adodb.connection',@obj out
if @err<>0 goto lberr

exec @err=sp_oamethod @obj,'open',null,@constr
if @err<>0 goto lberr

--創建表的SQL
declare @tbname sysname
set @tbname='##tmp_'+convert(varchar(38),newid())
set @sql='select * into ['+@tbname+'] from('+@sqlstr+') a'
exec(@sql)

select @sql='',@fdlist=''
select @fdlist=@fdlist+',['+a.name+']'
,@sql=@sql+',['+a.name+'] '
   +case
    when b.name like '%char'
    then case when a.length>255 then 'memo'
     else 'text('+cast(a.length as varchar)+')' end
    when b.name like '%int' or b.name='bit' then 'int'
    when b.name like '�tetime' then 'datetime'
    when b.name like '%money' then 'money'
    when b.name like '%text' then 'memo'
    else b.name end
FROM tempdb..syscolumns a left join tempdb..systypes b on a.xtype=b.xusertype
where b.name not in('image','uniqueidentifier','sql_variant','varbinary','binary','timestamp')
and a.id=(select id from tempdb..sysobjects where name=@tbname)

if @@rowcount=0 return

select @sql='create table ['+@sheetname
+']('+substring(@sql,2,8000)+')'
,@fdlist=substring(@fdlist,2,8000)

exec @err=sp_oamethod @obj,'execute',@out out,@sql
if @err<>0 goto lberr

exec @err=sp_oadestroy @obj

--導入數據
set @sql='openrowset(''MICROSOFT.JET.OLEDB.4.0'',''Excel 8.0;HDR=YES
    ;DATABASE='+@path+@fname+''',['+@sheetname+'$])'

exec('insert into '+@sql+'('+@fdlist+') select '+@fdlist+' from ['+@tbname+']')

set @sql='drop table ['+@tbname+']'
exec(@sql)
return

lberr:
exec sp_oageterrorinfo 0,@src out,@desc out
lbexit:
select cast(@err as varbinary(4)) as 錯誤號
   ,@src as 錯誤源,@desc as 錯誤描述
select @sql,@constr,@fdlist
go

原文出處:http://blog.sina.com.cn/s/blog_4a8552f80100hee8.html

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved