unit Unit_DBGridEhToExcel;
interface
uses
SysUtils, Variants, Classes, Graphics, Controls, Forms, Excel2000, ComObj,
Dialogs, DB, DBGridEh, windows,ComCtrls,ExtCtrls;
type
TDBGridEhToExcel = class(TComponent)
private
FProgressForm: TForm; {进度窗体}
FtempGauge: TProgressBar; {进度条}
FShowProgress: Boolean; {是否显示进度窗体}
FShowOpenExcel:Boolean; {是否导出后打开Excel文件}
FDBGridEh: TDBGridEh;
FTitleName: TCaption; {Excel文件标题}
FUserName: TCaption; {制表人}
procedure SetShowProgress(const Value: Boolean); {是否显示进度条}
procedure SetShowOpenExcel(const Value: Boolean); {是否打开生成的Excel文件}
procedure SetDBGridEh(const Value: TDBGridEh);
procedure SetTitleName(const Value: TCaption); {标题名称}
procedure SetUserName(const Value: TCaption); {使用人名称}
procedure CreateProcessForm(AOwner: TComponent); {生成进度窗体}
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure ExportToExcel; {输出Excel文件}
published
property DBGridEh: TDBGridEh read FDBGridEh write SetDBGridEh;
property ShowProgress: Boolean read FShowProgress write SetShowProgress; //是否显示进度条
property ShowOpenExcel: Boolean read FShowOpenExcel write SetShowOpenExcel; //是否打开Excel
property TitleName: TCaption read FTitleName write SetTitleName;
property UserName: TCaption read FUserName write SetUserName;
end;
implementation
constructor TDBGridEhToExcel.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FShowProgress := True;
FShowOpenExcel:= True;
end;
procedure TDBGridEhToExcel.SetShowProgress(const Value: Boolean);
begin
FShowProgress := Value;
end;
procedure TDBGridEhToExcel.SetDBGridEh(const Value: TDBGridEh);
begin
FDBGridEh := Value;
end;
procedure TDBGridEhToExcel.SetTitleName(const Value: TCaption);
begin
FTitleName := Value;
end;
procedure TDBGridEhToExcel.SetUserName(const Value: TCaption);
begin
FUserName := Value;
end;
function IsFileInUse(fName: string ): boolean;
var
HFileRes: HFILE;
begin
Result :=false;
if not FileExists(fName) then exit;
HFileRes :=CreateFile(pchar(fName), GENERIC_READ
or GENERIC_WRITE,, nil,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL, );
Result :=(HFileRes=INVALID_HANDLE_VALUE);
if not Result then
CloseHandle(HFileRes);
end;
procedure TDBGridEhToExcel.ExportToExcel;
var
XLApp: Variant;
Sheet: Variant;
s1, s2: string;
Caption,Msg: String;
Row, Col: integer;
iCount, jCount: Integer;
FBookMark: TBookmark;
FileName: String;
SaveDialog1: TSaveDialog;
begin
//如果数据集为空或没有打开则退出
if not DBGridEh.DataSource.DataSet.Active then Exit;
SaveDialog1 := TSaveDialog.Create(Nil);
SaveDialog1.FileName := TitleName + '_' + FormatDateTime('YYMMDDHHmmSS', now);
SaveDialog1.Filter := 'Excel文件|*.xls';
if SaveDialog1.Execute then
FileName := SaveDialog1.FileName;
SaveDialog1.Free;
if FileName = '' then Exit;
while IsFileInUse(FileName) do
begin
if Application.MessageBox('目标文件使用中,请退出目标文件后点击确定继续!',
'注意', MB_OKCANCEL + MB_ICONWARNING) = IDOK then
begin
end
else
begin
Exit;
end;
end;
if FileExists(FileName) then
begin
Msg := '已存在文件(' + FileName + '),是否覆盖?';
if Application.MessageBox(PChar(Msg), '提示', MB_YESNO + MB_ICONQUESTION + MB_DEFBUTTON2) = IDYES then
begin
//删除文件
DeleteFile(PChar(FileName))
end
else
exit;
end;
Application.ProcessMessages;
Screen.Cursor := crHourGlass;
//显示进度窗体
if ShowProgress then
CreateProcessForm(nil); if not VarIsEmpty(XLApp) then
begin
XLApp.DisplayAlerts := False;
XLApp.Quit;
VarClear(XLApp);
end;
//通过ole创建Excel对象
try
XLApp := CreateOleObject('Excel.Application');
except
MessageDlg('创建Excel对象失败,请检查你的系统是否正确安装了Excel软件!', mtError, [mbOk], );
Screen.Cursor := crDefault;
Exit;
end;
//生成工作页
XLApp.WorkBooks.Add[XLWBatWorksheet];
XLApp.WorkBooks[].WorkSheets[].Name := TitleName;
Sheet := XLApp.Workbooks[].WorkSheets[TitleName];
//写标题
sheet.cells[, ] := TitleName;
sheet.range[sheet.cells[, ], sheet.cells[, DBGridEh.Columns.Count]].Select; //选择该列
XLApp.selection.HorizontalAlignment := $FFFFEFF4; //居中
XLApp.selection.MergeCells := True; //合并
//写表头
Row := ;
jCount := ;
for iCount := to DBGridEh.Columns.Count - do
begin
Col := ;
Row := iCount+;
Caption := DBGridEh.Columns[iCount].Title.Caption;
while POS('|', Caption) > do
begin
jCount := ;
s1 := Copy(Caption, , Pos('|',Caption)-);
if s2 = s1 then
begin
sheet.range[sheet.cells[Col, Row-],sheet.cells[Col, Row]].Select;
XLApp.selection.HorizontalAlignment := $FFFFEFF4;
XLApp.selection.MergeCells := True;
end
else
Sheet.cells[Col,Row] := Copy(Caption, , Pos('|',Caption)-);
Caption := Copy(Caption,Pos('|', Caption)+, Length(Caption));
Inc(Col);
s2 := s1;
end;
Sheet.cells[Col, Row] := Caption;
Inc(Row);
end;
//合并表头并居中
if jCount = then
for iCount := to DBGridEh.Columns.Count do
if Sheet.cells[, iCount].Value = '' then
begin
sheet.range[sheet.cells[, iCount],sheet.cells[, iCount]].Select;
XLApp.selection.HorizontalAlignment := $FFFFEFF4;
XLApp.selection.MergeCells := True;
end
else begin
sheet.cells[, iCount].Select;
XLApp.selection.HorizontalAlignment := $FFFFEFF4;
end;
//读取数据
DBGridEh.DataSource.DataSet.DisableControls;
FBookMark := DBGridEh.DataSource.DataSet.GetBookmark;
DBGridEh.DataSource.DataSet.First;
while not DBGridEh.DataSource.DataSet.Eof do
begin
for iCount := to DBGridEh.Columns.Count do
begin
//Sheet.cells[jCount, iCount] :=DBGridEh.Columns.Items[iCount-1].Field.AsString; case DBGridEh.DataSource.DataSet.FieldByName(DBGridEh.Columns.Items[iCount-].FieldName).DataType of
ftSmallint, ftInteger, ftWord, ftAutoInc, ftBytes:
Sheet.cells[jCount, iCount] :=DBGridEh.Columns.Items[iCount-].Field.asinteger;
ftFloat, ftCurrency, ftBCD:
Sheet.cells[jCount, iCount] :=DBGridEh.Columns.Items[iCount-].Field.AsFloat;
else
if DBGridEh.DataSource.DataSet.FieldByName(DBGridEh.Columns.Items[iCount-].FieldName) is TBlobfield then // 此类型的字段(图像等)暂无法读取显示
Sheet.cells[jCount, iCount] :=DBGridEh.Columns.Items[iCount-].Field.AsString
else
Sheet.cells[jCount, iCount] :=''''+DBGridEh.Columns.Items[iCount-].Field.AsString;
end; end;
Inc(jCount);
//显示进度条进度过程
if ShowProgress then
begin
FtempGauge.Position := DBGridEh.DataSource.DataSet.RecNo;
FtempGauge.Refresh;
end;
DBGridEh.DataSource.DataSet.Next;
end;
if DBGridEh.DataSource.DataSet.BookmarkValid(FBookMark) then
DBGridEh.DataSource.DataSet.GotoBookmark(FBookMark);
DBGridEh.DataSource.DataSet.EnableControls;
//读取表脚
if DBGridEh.FooterRowCount > then
begin
for Row := to DBGridEh.FooterRowCount- do
begin
for Col := to DBGridEh.Columns.Count- do
Sheet.cells[jCount, Col+] := DBGridEh.GetFooterValue(Row,DBGridEh.Columns[Col]);
Inc(jCount);
end;
end;
//调整列宽
// for iCount := 1 to DBGridEh.Columns.Count do
// Sheet.Columns[iCount].EntireColumn.AutoFit;
sheet.cells[, ].Select;
XlApp.Workbooks[].SaveAs(FileName);
XlApp.Visible := True;
XlApp := Unassigned;
if ShowProgress then
FreeAndNil(FProgressForm);
Screen.Cursor := crDefault; end;
destructor TDBGridEhToExcel.Destroy;
begin
inherited Destroy;
end;
procedure TDBGridEhToExcel.CreateProcessForm(AOwner: TComponent);
var
Panel: TPanel;
begin
if Assigned(FProgressForm) then
exit;
FProgressForm := TForm.Create(AOwner);
with FProgressForm do
begin
try
Font.Name := '宋体'; {设置字体}
Font.Size := ;
BorderStyle := bsNone;
Width := ;
Height := ;
BorderWidth := ;
Color := clBlack;
Position := poScreenCenter;
Panel := TPanel.Create(FProgressForm);
with Panel do
begin
Parent := FProgressForm;
Align := alClient;
Caption := '正在导出Excel,请稍候......';
Color:=$00E9E5E0;
end;
FtempGauge:=TProgressBar.Create(Panel);
with FtempGauge do
begin
Parent := Panel;
Align:=alClient;
Min := ;
Max:= DBGridEh.DataSource.DataSet.RecordCount;
Position := ;
end;
except
end;
end;
FProgressForm.Show;
FProgressForm.Update;
end;
procedure TDBGridEhToExcel.SetShowOpenExcel(const Value: Boolean);
begin
FShowOpenExcel:=Value;
end;
end.

调用:

var
DbOut : TDBGridEhToExcel;
begin
DbOut := TDBGridEhToExcel.Create(Self);
DbOut.TitleName := Caption;
DbOut.ShowProgress := True;
DbOut.ShowOpenExcel := True;
DbOut.DBGridEh := DBGridEh1;
DbOut.ExportToExcel;
FreeAndNil(DbOut);

Delphi DBGridEh导出Excel的更多相关文章

  1. (转载)DBGridEh导出Excel等格式文件

    DBGridEh导出Excel等格式文件 uses DBGridEhImpExp; {--------------------------------------------------------- ...

  2. Delphi TXLSReadWriteII导出Excel

    TXLSReadWriteII导出Excle (有点复杂,可以自己简化一下,直接从项目中抓取的) procedure TformSubReport.DataToExcel(_Item: Integer ...

  3. Delphi+DBGrid导出Excel

    uses ComObj; //DBGrid:指定的DBGrid;SaveFileName:要保存的文件名 function ExportDBGrid(DBGrid: TDBGrid; SaveFile ...

  4. delphi cxgrid导出excel去除货币符号

    版本 : devexpress 13.1.4 打开 包在ExpressExportLibary目录中.  修改FCells.SetCellDataCurrency为FCells.SetCellData ...

  5. Delphi TXLSReadWriteII 导出EXCEL

    unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms ...

  6. Delphi 数据导出到Excel

    好多办公软件特别是财务软件,都需要配备把数据导出到Excel,下面就来介绍两种数据导出方法 1.ADODB导出查询结果(此方法需要安装Excel) 2.二维表数据导出(根据Excel文件结构生成二进制 ...

  7. CxGrid导出Excel时清除颜色的设置

    CxGrid导出Excel时清除颜色的设置 (2011-04-25 16:33:23) 转载▼ 标签: it 分类: Delphi http://www.radxe.com/?p=170 cxgrid ...

  8. C#使用Aspose.Cells导出Excel简单实现

    首先,需要添加引用Aspose.Cells.dll,官网下载地址:http://downloads.aspose.com/cells/net 将DataTable导出Xlsx格式的文件下载(网页输出) ...

  9. 利用poi导出Excel

    import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException;import java.lang.r ...

随机推荐

  1. 搭建内部NuGet服务

    简介 NuGet相当于Python中的pip,nodejs中的npm,用来管理.net/.net core的程序集版本,也叫包管理器.在框架化.模块化开发中使用nuget服务必不可少,尤其是在abp开 ...

  2. 时序数据库influxDB存储数据grafana展示数据

    一.influxDB简介 InfluxDB是一款用Go语言编写的开源分布式时序.事件和指标数据库,无需外部依赖.该数据库现在主要用于存储涉及大量的时间戳数据,如DevOps监控数据,APP metri ...

  3. JAVA项目中的常用的异常处理情况总结

    可能遇见的异常或错误: 检查性异常:最具代表的检查性异常是用户错误或问题引起的异常,这是程序员无法预见的.例如要打开一个不存在文件时,一个异常就发生了,这些异常在编译时不能被简单地忽略. 运行时异常: ...

  4. poi导出excel数据量过大

    问题:使用poi导出excel,数据量过大导致内存溢出 解决思路:1.多sheet导出 2.生成多个excel打包下载 3.生成csv下载 本文使用的是第二个思路,代码如下: poiUtil工具类 p ...

  5. 用Python实现九九乘法表打印

    #!usr/bin/env python # -*- coding:utf-8 -*- # dic={ # 'apple':10, # 'iphon':5000, # 'wwatch Tv':3000 ...

  6. 在vue2.0中使用bootstarpTable(jquery+bootstarp+bootstarpTable)

    ​ 要想使用bootstarp-table就需要按顺序引入 jquery > bootstarp > bootstarp-table //路径可能会有变动 最好在node_modules ...

  7. 【leetcode】1252. Cells with Odd Values in a Matrix

    题目如下: Given n and m which are the dimensions of a matrix initialized by zeros and given an array ind ...

  8. layui 批量上传

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="piclist.aspx.c ...

  9. CSS 内边距 padding 属性

    CSS padding 属性定义元素边框与元素内容之间的空白区域. ㈠padding(填充) ⑴当元素的 padding(填充)内边距被清除时,所释放的区域将会受到元素背景颜色的填充. ⑵单独使用 p ...

  10. HGOI 20190822 OCWA提高组模拟赛二

    Problem A 快递 根节点为$1$ , 含有$n$个节点的树,每一条边都有一段开放的时间$[s_i,e_i]$,和经过需要的时间. 有$q$组询问,每一次在时刻$t_i$出发从根节点出发走到第$ ...