淺談crystal reports在VB中的調用
2024-07-21 02:25:35
供稿:網友
環境:vb6.0,crystal reports 9.0
在一個項目中用到了crystal reports,總結一些經驗和教訓。
以做一張單據的套打為例。
單據包括單據頭,單據體。單據頭和單據體可能是一對多的關系。并且他們分別存在于兩張表當中,用字段fid做關聯。要求能夠動態的傳入參數fid,顯示不同的結果。
首先,打開crystal reports,做好一張單據的模板rpt。制作報表的方法有很多,比如:用它的圖形化工具直接建立幾個表之間的連接,然后將想要顯示的字段托到報表當中;或是調用一個已經寫好的存儲過程;或是直接編輯command。再將想要顯示的字段托到報表當中。然而,經常問題就出在這里,用圖形化工具制作的報表,在vb中給此報表傳入datasource時經常會因為字段不對應,而導致部分數據無法顯示。所以建議在crystal reports中利用command編輯sql語句,制作單據。然后將此sql語句copy到vb代碼中,生成新的結果集,并賦給rpt文件新的數據源。以此保證各字段的對應。
假定單據頭信息存放于表quotation中,單據體存放于表quotationentry中。單據頭信息中需要顯示字段客戶名稱fcustomer,單據編號fbillno,單據日期fbilldate,制單人fbiller......;單據體需要顯示的是商品明細,包括商品代碼fnumber,商品款式fstyle,商品大小fsize,商品顏色fcolor......兩表關聯字段fid。
于是,在rpt文件的command中添入sql語句”select a.*,b.* from quotation a left join quotationentry b on a.fid=b.fid”。然后將需要的字段拉入報表當中。
在vb中,首先應用crystal reports 9 actionx designer disign and runtime library,并添加部件crystal report viewer control 9。
在form中添加剛才加入的部件。就可以調用并顯示了。
public billid as integer '傳入的參數
private sub command1_click()
dim capp as new craxddrt.application
dim carp as new craxddrt.report
dim conn as new connection
dim rs as new recordset
dim sql as string
conn.connectionstring = "provider=sqloledb.1;password=sa;persist security info=true;user id=sa;initial catalog=ais20041209121508;data source=127.0.0.1"
sql = "select a.*,b.* from quotation a left join quotationentry b on a.fid=b.fid where a.fid="&billid
with conn
.open
rs.open sql, conn, adopenstatic, adlockbatchoptimistic
end with
set carp = capp.openreport("e:/code/component/client/quotation.rpt")
carp.discardsaveddata '清空以前數據
carp.database.setdatasource rs
crviewer91.reportsource = carp
crviewer91.viewreport
end sub
也可以將寫好的quotation.rpt文件一起打包到vb當中,具體的辦法是在vb工程的右鍵加載crystal report 9的設計器,選擇打開以有的文件,打開e:/code/component/client/quotation.rpt,并加載到其中。以上的代碼set carp = capp.openreport("e:/code/component/client/quotation.rpt")就可以不要了,直接將carp替換為加載進來的控件名稱。
菜鳥學堂: