问题描述
Primefaces 5.0中有一个DataGrid组件.它显示按行划分的输入数据.如何显示按列拆分的数据?
There is a DataGrid component in Primefaces 5.0. It shows input data split by rows.How to show data split by columns?
A B C A D G
D E F --> B E H
G H C F
推荐答案
我要在Primefaces的DataGrid组件中转置数据的解决方案是重写DataGridRenderer
类的encodeTable()
方法.
My solution to have transposed data in DataGrid component of Primefaces is to override encodeTable()
method of DataGridRenderer
class.
@Override
protected void encodeTable(FacesContext context, DataGrid grid) throws IOException {
ResponseWriter writer = context.getResponseWriter();
int columns = grid.getColumns();
int firstRowIndex = grid.getFirst();
int rowIndex = firstRowIndex;
int rows = grid.getRows();
int itemsToRender = rows != 0 ? rows : grid.getRowCount();
int numberOfRowsToRender = (itemsToRender + columns - 1) / columns;
String transpose = (String) grid.getAttributes().get("transpose");
boolean isTranspose = transpose != null ? Boolean.valueOf(transpose) : false;
writer.startElement("table", grid);
writer.writeAttribute("class", DataGrid.TABLE_CLASS, null);
writer.startElement("tbody", null);
for (int i = 0; i < numberOfRowsToRender; i++) {
writer.startElement("tr", null);
writer.writeAttribute("class", DataGrid.TABLE_ROW_CLASS, null);
for (int j = 0; j < columns; j++) {
writer.startElement("td", null);
writer.writeAttribute("class", DataGrid.TABLE_COLUMN_CLASS, null);
if (isTranspose) {
writer.writeAttribute("style", String.format("width: %d%%;", 100 / columns), null);
}
grid.setRowIndex(isTranspose ? numberOfRowsToRender * j + i + firstRowIndex : rowIndex);
if (grid.isRowAvailable()) {
renderChildren(context, grid);
}
rowIndex++;
writer.endElement("td");
}
writer.endElement("tr");
}
grid.setRowIndex(-1); //cleanup
writer.endElement("tbody");
writer.endElement("table");
}
并在faces-config.xml
中注册Renderer元素:
And register Renderer element within the faces-config.xml
:
<render-kit>
<renderer>
<component-family>org.primefaces.component</component-family>
<renderer-type>org.primefaces.component.DataGridRenderer</renderer-type>
<renderer-class>org.primefaces.component.datagrid.TransposableDataGridRenderer</renderer-class>
</renderer>
</render-kit>
现在,我可以为<p:dataGrid>
标签指定transposable="true"
属性.该代码还可以修复"样式表,以使每页具有相同的列数,即使在最后一页上没有足够的数据覆盖所有列.
Now I can specify transposable="true"
attribute for <p:dataGrid>
tag.The code is also 'fixing' stylesheet to have the same number of columns for every page even if on the last page there is not enough data to cover all columns.
这篇关于如何按列而不是按行输出Primefaces DataGrid组件的数据(转置数据)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!