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. MSSQL日期分组排序

    等于今天日期的排上面,大于今天的排中间,小于今天的排下面,带分页.

  2. session共享原理以及PHP 实现多网站共享用户SESSION 数据解决方案

    参考自: http://www.cnblogs.com/qulinke/articles/6003049.html https://segmentfault.com/q/101000000578847 ...

  3. JULY-Record-update

    2019/07/26~2019/07/29,关于学习的一些记录 神经网络和深度学习neural networks and deep-learning-中文_ALL(1) 张景,逻辑派,组织派,行为主义 ...

  4. html中表单提交

    表单提交代码 1.源代码分析 <!DOCTYPE html> <html lang="en"> <head> <meta charset= ...

  5. pymysql操作数据库、索引、慢日志管理

    目录 pymysql操作数据库 简单操作 sql的注入问题 sql注入问题解决办法 sql注入问题模板总结 利用pymysql操作数据库 (增删改),conn.commit() 索引 1.为何要有索引 ...

  6. buuctf@easyre

  7. Python入门提示

    Python入门提示——行与缩进,常量定义 在初学Python时,除了学习一些标准的语法外,会遇到一些其他困难,列举如下. 一.python http://www.xuanhe.net/的行与缩进 P ...

  8. k8s配置文件模板

    一,deployment Deployment为Pod和Replica Set下一代Replication Controller)提供声明式更新 1,配置示例 apiVersion: apps/v1 ...

  9. cursor(鼠标手型)属性

    ㈠简单介绍 在浏览网页时,通常看到的鼠标光标形状有箭头.手形.沙漏等,而在 windows 中实际看到的鼠标指针种类比这个还要多. 一般情况下,鼠标光标的形状由浏览器负责控制,大多数情况的光标形状为箭 ...

  10. 静态库lib、动态库dll基础

    首先从hello world!开始 //main.cpp文件 void cpu(); int main() { put(); ; } 在main.cpp中定义了一个cpu():函数,但没有实现其功能, ...