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. 09Cookie&Session

    1.会话技术 1. 会话:一次会话中包含多次请求和响应.  一次会话:浏览器第一次给服务器资源发送请求,会话建立,直到有一方断开为止2. 功能:在一次会话的范围内的多次请求间,共享数据3. 方式: 1 ...

  2. LogHelper

    原文链接 public class LogHelper { static string strLogCOMPath = Directory.GetCurrentDirectory() + " ...

  3. docker 创建容器时指定容器ip

    Docker创建容器时默认采用bridge网络,自行分配ip,不允许自己指定. 在实际部署中,我们需要指定容器ip,不允许其自行分配ip,尤其是搭建集群时,固定ip是必须的. 我们可以创建自己的bri ...

  4. shell知识点(二)

    Shell 中的数组 Shell 数组用括号来表示,元素用"空格"符号分割开,语法格式如下: 方式2: arr=(value1 value2 value3)   (这种方式带值) ...

  5. Ubuntu安装opencv 为调用gpu模块

    也真够折腾的. 事件背景:为了一个光流的提取处理,本来是3.1的opencv在include一些模块上出错,原因是opencv3.0以上的版本对模块进行了再分离,要contribute,但是contr ...

  6. [洛谷P1607] 庙会班车

    题目描述 Although Farmer John has no problems walking around the fair to collect prizes or see the shows ...

  7. 【传输管理③】Client集团间的传输(例:开发环境300→310,300→320)

    之前有提到: 每个环境可能有若干个Client(客户端/集团),且每个Client用途都不一样. 如下图所示,开发环境就有300,310和320三个Client. 假设开发人员在Client300中新 ...

  8. IntelliJ IDEA常用快捷键总结

    之前开发项目一直用的是eclipse进行开发,近期在使用IDEA这个工具进行项目开发,之前在eclipse上能使用的快捷键方法放在IDEA上很多都不适用了,因此在此总结一下关于IDEA快捷键的使用方法 ...

  9. Qt:路径问题小结

    在做Qt项目的时候,我们难免遇到到文件路径问题. 如QFile file("text.txt")加载不成功.QPixmap("../text.png") 加载图 ...

  10. maven项目创建4 dao层整合

    项目配置文件要放在打包成war包的web项目中 创建文件步骤 1    SqlMapConfig.xml <?xml version="1.0" encoding=" ...