码迷,mamicode.com
首页 > 数据库 > 详细

delphi dbgrid数据导出为excel

时间:2019-06-07 12:49:59      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:ati   creat   ems   book   work   proc   create   安装   var   

uses Excel2000,ComObj;

procedure F_Form.Button1Click(Sender: TObject);
var
    myExcel:TExcel;
    Int_i,Int_j,rowCount,columnCount:Integer;
    ExcelId:Variant;
begin
  try
      ExcelId:=CreateOleObject(‘Excel.Application‘);
  except
      on Exception do raise Exception.Create(‘无法创建报表,请确认是否安装EXCEL‘);
  end;

  if DBGrid4.DataSource.DataSet.RecordCount<>0 then
  begin
      rowCount:=DBGrid4.DataSource.DataSet.RecordCount;
      columnCount := DBGrid4.FieldCount;
        try
            Excelid.Visible := True;
            Excelid.WorkBooks.Add;
            Excelid.WorkSheets[1].Range[‘A1:I1‘].Merge(True);
            Excelid.WorkSheets[1].Cells[1,1].Value :=  ‘xxx公司‘;

            Excelid.WorkSheets[1].Range[‘A2:I2‘].Merge(True);
            Excelid.WorkSheets[1].Cells[2,1].Value := ‘xxx信息统计表‘;

            excelid.worksheets[1].cells[3,1].value:=‘1;
            excelid.worksheets[1].cells[3,2].value:=‘2;
            excelid.worksheets[1].cells[3,3].value:=‘3‘;
            excelid.worksheets[1].cells[3,4].value:=‘4;
            excelid.worksheets[1].cells[3,5].value:=‘5;
            excelid.worksheets[1].cells[3,6].value:=‘6;
            excelid.worksheets[1].cells[3,7].value:=‘7;
            excelid.worksheets[1].cells[3,8].value:=‘8‘;
            excelid.worksheets[1].cells[3,9].value:=‘9;
            excelid.worksheets[1].cells[3,10].value:=‘10;

            Excelid.WorkSheets[1].Range[‘A1:T3‘].Font.Name :=‘宋体‘;
            Excelid.WorkSheets[1].Range[‘A1:I2‘].Font.Size :=12;
            Excelid.WorkSheets[1].Range[‘A2:T3‘].Font.Size :=10;
            Excelid.WorkSheets[1].Range[‘A1:T3‘].Font.Bold :=True;

            DBGrid4.DataSource.DataSet.First();
            for Int_i:=0 to rowCount do
            begin
              for Int_j:=0 to columnCount-1 do
              begin
                ExcelId.worksheets[1].cells[Int_i+4,int_j+1].value:=  DBGrid4.DataSource.DataSet.FieldByName(DBGrid4.Columns.Items[int_j].FieldName).AsString;
              end;
              DBGrid4.DataSource.DataSet.Next();
            end;

            Excelid.WorkSheets[1].range[‘A1:T3‘].HorizontalAlignment := $FFFFEFF4;
            Excelid.worksheets[1].range[‘A1:T3‘].VerticalAlignment := $FFFFEFF4;
            Excelid.Columns.AutoFit;

        finally
        end;

  end;
end;

delphi dbgrid数据导出为excel

标签:ati   creat   ems   book   work   proc   create   安装   var   

原文地址:https://www.cnblogs.com/jijm123/p/10987845.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!