首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

C++ Builder 從 DBGrid 自動產生並可自訂的報表

     編輯:關於C++

動態生成 QuickReport 報表並開放使用者微調版面

針對大量報表需求,利用動態建立元件技術,讀取 TDBGrid 的欄位標題、寬度、字型、對齊等屬性,在 TQuickRep 上自動建立對應的 TQRLabel (標題)、TQRDBText (資料)、TQRShape (格線),並封裝為 TGridPrint 類別,對外提供設定總標題、欄寬、標題列高、資料列高等介面供使用者自訂。

類別定義 (GridPrint.h)

struct NEWFIELDTYPE {
    AnsiString sTitle;      // 欄位標題
    int iWidth;             // 欄寬
    TQRLabel *pLabel;       // 標題標籤
    TQRDBText *pDBText;     // 資料文字
    TQRShape *pShapeTitle;  // 標題列分隔線
    TQRShape *pShapeData;   // 資料列分隔線
};

class TGridPrint {
public:
    TGridPrint(TQuickRep *pSrcQuickRep, TDBGrid *pSrcDBGrid,
               TQRBand *SrcTitleBand1, TQRBand *SrcColumnHeaderBand1,
               TQRBand *SrcDetailBand1);
    ~TGridPrint();
    void DoPreview();                       // 列印預覽
    void SetPrntTitle(AnsiString sTitle);   // 設定總標題
    void SetColumnsWidth(int *ColumnsWidth);// 設定各欄寬度
    void SetHeadRectHeight(int iHeight);    // 設定標題列高
    void SetDetailRectHeight(int iHeight);  // 設定資料列高
private:
    TDBGrid *pDBGrid; TDataSet *pDataSet; TQuickRep *pQuickRep;
    TQRBand *TitleBand1, *ColumnHeaderBand1, *DetailBand1;
    TQRLabel *pTitleLabel;
    TQRShape *pHeadRect, *pDetailRect;
    int iHeadRectHeight, iDetailRectHeight, _iTotalWidth, _iIntClearance, _iFieldCount;
    NEWFIELDTYPE _arrayFieldType[40]; // 支援最多 40 欄位
    void AutoAdjustColumnsWidth();    // 自動調整欄寬
};

建構函數核心邏輯 (GridPrint.cpp)

  1. 依參數設定私有變數,綁定 DataSet。
  2. 建立總標題標籤置中。
  3. 計算總寬度,超過報表寬則按比例縮減 (AutoAdjustColumnsWidth)。
  4. 建立標題列與資料列外框矩形 (TQRShape)。
  5. 迴圈動態建立各欄位:標題標籤 (複製 DBGrid 標題屬性)、資料文字 (設定 DataField/Font/Alignment)、左右分隔線。

解構函數

依序釋放所有動態建立的元件 (Label, DBText, Shape)。

使用範例

#include "GridPrint.h"
#include "RepRst.h" // 包含 TQuickRep 的表單

TFrmRepRst *pFrmRepRst = new TFrmRepRst(NULL);
TGridPrint *pGridPrint = new TGridPrint(
    pFrmRepRst->QuickRep1, DBGrid1,
    pFrmRepRst->TitleBand1, pFrmRepRst->ColumnHeaderBand1, pFrmRepRst->DetailBand1);
pGridPrint->DoPreview();
delete pGridPrint; delete pFrmRepRst;

優點

  • 程式設計師只需幾行程式碼即可產生報表,大幅減少手工設計時間。
  • 使用者可透過介面微調欄寬、列高、總標題,彈性更高。
  • 封裝類別可繼承擴充,符合 OOP 精神。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved