早期專案多使用 ReportMachine 開發報表,但轉向 B/S 架構後,因其 Web 端預覽頻繁失敗、需調整電腦安全等級、缺乏完善文件與技術支援等問題,團隊決定改用 DevExpress XtraReports。以下整理實作過程中的關鍵技術點,供開發者參考。
建議使用 RibbonEndUserDesignerDemo 進行報表設計,而非直接在 Visual Studio 中操作。該工具提供更直觀的リボン式介面,支援拖曳排版、即時預覽,能大幅提升設計效率,尤其適合複雜的中式報表佈局。
核心程式碼如下,透過路徑配置載入 .repx 範本,並將 DataSet 指派為資料來源:
Dim rpt As New DevExpress.XtraReports.UI.XtraReport
rpt.LoadLayout(MapPath(Common.ConfigHelper.GetConfigString("ReportFile")) & "CerDetail.repx")
rpt.DataSource = ds
ReportViewer1.Report = rpt
若遇到 ds.Tables.Add(dt) 提示「Table 已存在」,請先為 DataTable 指定唯一名稱:
Dim dt As New DataTable
dt = sm.GetList_CerEmp("").Copy
dt.TableName = "CerEmp" ' 自訂唯一名稱
ds.Tables.Add(dt)
動態新增參數並設定 RequestParameters = False 以禁止使用者介面輸入:
Dim rp As New DevExpress.XtraReports.UI.XtraReport
Dim item As New DevExpress.XtraReports.Parameters.Parameter
item.Name = "ParamName"
item.Value = "ParamValue"
rp.Parameters.Add(item)
rp.RequestParameters = False
利用 FillEmptySpace 事件動態建立 XRTable 填充剩餘空間,並在第一行標示「以下空白」:
Private Sub OnFillEmptySpace(ByVal sender As Object, ByVal e As DevExpress.XtraReports.UI.BandEventArgs)
Dim Tab As New XRTable()
Tab.Size = New Size(692, e.Band.Height)
Tab.Location = New Point(8, 0)
Tab.BorderWidth = 1
Tab.Borders = DevExpress.XtraPrinting.BorderSide.All
For i As Integer = 1 To Convert.ToInt32(e.Band.Height / Me.tableCell18.Height)
Dim row As New XRTableRow()
Row.Size = New Size(692, 25)
Row.Cells.AddRange(CreateArrayOfCells(i))
Tab.Rows.Add(Row)
Next
e.Band.Controls.Add(Tab)
End Sub
Private Function CreateArrayOfCells(ByVal n As Integer) As XRTableCell()
Dim CellCollection(4) As XRTableCell
For i As Integer = 0 To 4
CellCollection(i) = New XRTableCell()
CellCollection(i).TextAlignment = TextAlignment.MiddleCenter
If n = 1 AndAlso i = 0 Then
CellCollection(0).Font = New Font("楷體_GB2312", 9)
CellCollection(0).Text = "以下空白"
End If
' 依欄位索引設定寬度
Select Case i
Case 0 : CellCollection(i).Size = New Size(67, 25)
Case 1 : CellCollection(i).Size = New Size(118, 25)
Case 2 : CellCollection(i).Size = New Size(57, 25)
Case 3 : CellCollection(i).Size = New Size(214, 25)
Case 4 : CellCollection(i).Size = New Size(236, 25)
End Select
Next
Return CellCollection
End Function
預設字體(如新細明體)在列印或匯出 PDF 時易出現方塊字。實測推薦使用以下字體可正確顯示中文:
建議在報表設計階段統一套用上述字體,並確認伺服器端已安裝對應字型檔,以免部署環境缺字導致異常。
以上心得為實務操作總結,若有更佳作法歡迎交流指正。