FastReport教程:如何使列突出顯示,具體取決于列的值
Matrix報表是分析數據的絕佳工具。實質上,分析報表中的矩陣是一個匯總表。“條件分配”通常用于促進分析。這是FastReport.Net中的常規工具。條件突出顯示意味著使用顏色,字體或圖標突出顯示數據單元格,具體取決于給定條件。但是,條件突出顯示適用于個人但是如果我們想根據標題中的值選擇整個列呢?例如,要突出顯示周末。在這種情況下,您將不得不訴諸報表的“無所不能”腳本,常規顏色突出顯示在這里沒有幫助。
使用基于nwind.xml演示數據庫中的MatrixDemo表的矩陣創建模板:
我們的想法是在標題中找到滿足條件的值。在這個矩陣中,我們按年度計算員工的收入。
讓我們突出顯示標題為2012和2014的列。要執行此操作,我們需要突出顯示此列中的標題以及所有后續單元格,包括總計。為矩陣創建BeforePrint事件:
// List of selected columns private List<int> markedColumns; // Counter for columns in the first row private int firstLineColumn; // Counter for columns in the following lines private int secondLineColumn; // Matrix event handler private void Matrix2_BeforePrint(object sender, EventArgs e) { // Create a new list for selected columns markedColumns = new List<int>(); // Reset the first row counter firstLineColumn = 0; // Reset the next row count secondLineColumn = 0; }
最初,我們添加了幾個我們將在事件處理程序中使用的變量。這些變量存儲行的標記列。此外,在顯示矩陣之前,我們初始化變量。
為值為[Year]的單元格的BeforePrint事件創建另一個處理程序:
// Event handler for cells in the first row of the matrix private void Cell18_BeforePrint(object sender, EventArgs e) { // Use sender as TableCell TableCell cell = sender as TableCell; // Check the required value in the cell if (cell.Text == "2012" || cell.Text == "2014") { // Sets the fill color for this cell. cell.FillColor = Color.Brown; // Save to selected list of columns markedColumns.Add(firstLineColumn); } // Increase column count for first row firstLineColumn++; }
在這里,我需要做一個小的評論,以便你了解正在發生的事情的本質。關鍵是在FastReport中構建報表時的矩陣輸出是逐行完成的。因此,我們保存矩陣第一行的列號。在我們的例子中,2個值將落入標記列的列表中。
現在為值為[Revenue]的單元格添加事件處理程序:
// The event handler for the cells in the following rows of the matrix. You need to set it for the second row and the totals. private void Cell21_BeforePrint(object sender, EventArgs e) { // Use sender as TableCell TableCell cell = sender as TableCell; // Find the current index in the markedColumns list if (markedColumns.IndexOf(secondLineColumn) != -1) { // Sets the fill color for this cell. cell.FillColor = Color.Red; } // Increase counter secondLineColumn++; // Reset counter for next row if (secondLineColumn >= firstLineColumn) secondLineColumn = 0;
在此處理程序中,我們找到與第一行中所選列對應的列,并將其單元格繪制為紅色。到達最后一列后,重置下一行的變量。如您所知,在構建報表時,矩陣的第二行是動態的。這意味著它將顯示在源中的每行數據。因此,我們需要檢查每一行并為正確列中的單元格著色。
腳本中給出的解決方案是不尋常的,但對于這種情況唯一可能的解決方案,因為矩陣是動態構建的,并且不存儲單元格的最終結構,坐標和位置,直到它直接在工作表上繪制。只有模板(我們在設計器中看到的模板)和矩陣標題的文本值存儲在內存中。
因此,我們必須遍歷所有行并記住列以進行著色。
根據腳本,我們必須為矩陣創建三個事件處理程序BeforePrint,單元格[Year]和單元格[Revenue]。但是,在我們的矩陣中還有另一個第三行。它顯示結果,根據所選列繪制它們也是很好的。為此,對于位于[Revenue]下的單元格,只需從同一[Revenue]掛鉤BeforeFrint事件處理程序:
現在,運行報表:
如果要以不同的顏色繪制總計,則必須為總計的單元格創建自己的BeforePrint事件處理程序,類似于[Revenue]單元格的處理程序。
購買FastReport.Net正版授權,請點擊“”喲!